home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 1.iso / util / tgrep20.zip / REGEX.C < prev    next >
C/C++ Source or Header  |  1994-04-02  |  167KB  |  4,984 lines

  1. /* Extended regular expression matching and search library,
  2.    version 0.12.
  3.    (Implements POSIX draft P10003.2/D11.2, except for
  4.    internationalization features.)
  5.  
  6.    Copyright (C) 1993 Free Software Foundation, Inc.
  7.  
  8.    This program is free software; you can redistribute it and/or modify
  9.    it under the terms of the GNU General Public License as published by
  10.    the Free Software Foundation; either version 2, or (at your option)
  11.    any later version.
  12.  
  13.    This program is distributed in the hope that it will be useful,
  14.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  15.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16.    GNU General Public License for more details.
  17.  
  18.    You should have received a copy of the GNU General Public License
  19.    along with this program; if not, write to the Free Software
  20.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  21.  
  22. /* AIX requires this to be the first thing in the file. */
  23. #define _GNU_SOURCE
  24.  
  25. /* We need this for `regex.h', and perhaps for the Emacs include files.  */
  26. #include <sys/types.h>
  27. #include <string.h>
  28. #ifndef bcmp
  29. #define bcmp(s1, s2, n)    memcmp ((s1), (s2), (n))
  30. #endif
  31. #ifndef bcopy
  32. #define bcopy(s, d, n)    memcpy ((d), (s), (n))
  33. #endif
  34. #ifndef bzero
  35. #define bzero(s, n)    memset ((s), 0, (n))
  36. #endif
  37.  
  38. #include <stdlib.h>
  39. #include <malloc.h>
  40.  
  41.  
  42. /* Define the syntax stuff for \<, \>, etc.  */
  43.  
  44. /* This must be nonzero for the wordchar and notwordchar pattern
  45.    commands in re_match_2.  */
  46. #ifndef Sword 
  47. #define Sword 1
  48. #endif
  49.  
  50. #ifdef SYNTAX_TABLE
  51.  
  52. extern char *re_syntax_table;
  53.  
  54. #else /* not SYNTAX_TABLE */
  55.  
  56. /* How many characters in the character set.  */
  57. #define CHAR_SET_SIZE 256
  58.  
  59. static char re_syntax_table[CHAR_SET_SIZE];
  60.  
  61. static void
  62. init_syntax_once (void)
  63. {
  64.    register int c;
  65.    static int done = 0;
  66.  
  67.    if (done)
  68.      return;
  69.  
  70.    bzero (re_syntax_table, sizeof re_syntax_table);
  71.  
  72.    for (c = 'a'; c <= 'z'; c++)
  73.      re_syntax_table[c] = Sword;
  74.  
  75.    for (c = 'A'; c <= 'Z'; c++)
  76.      re_syntax_table[c] = Sword;
  77.  
  78.    for (c = '0'; c <= '9'; c++)
  79.      re_syntax_table[c] = Sword;
  80.  
  81.    re_syntax_table['_'] = Sword;
  82.  
  83.    done = 1;
  84. }
  85.  
  86. #endif /* not SYNTAX_TABLE */
  87.  
  88. #define SYNTAX(c) re_syntax_table[c]
  89.  
  90. /* Get the interface, including the syntax bits.  */
  91. #include "regex.h"
  92.  
  93. /* isalpha etc. are used for the character classes.  */
  94. #include <ctype.h>
  95.  
  96. /* Jim Meyering writes:
  97.  
  98.    "... Some ctype macros are valid only for character codes that
  99.    isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
  100.    using /bin/cc or gcc but without giving an ansi option).  So, all
  101.    ctype uses should be through macros like ISPRINT...  If
  102.    STDC_HEADERS is defined, then autoconf has verified that the ctype
  103.    macros don't need to be guarded with references to isascii. ...
  104.    Defining isascii to 1 should let any compiler worth its salt
  105.    eliminate the && through constant folding."  */
  106. #if ! defined (isascii) || defined (STDC_HEADERS)
  107. #undef isascii
  108. #define isascii(c) 1
  109. #endif
  110.  
  111. #ifdef isblank
  112. #define ISBLANK(c) (isascii (c) && isblank (c))
  113. #else
  114. #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
  115. #endif
  116. #ifdef isgraph
  117. #define ISGRAPH(c) (isascii (c) && isgraph (c))
  118. #else
  119. #define ISGRAPH(c) (isascii (c) && isprint (c) && !isspace (c))
  120. #endif
  121.  
  122. #define ISPRINT(c) (isascii (c) && isprint (c))
  123. #define ISDIGIT(c) (isascii (c) && isdigit (c))
  124. #define ISALNUM(c) (isascii (c) && isalnum (c))
  125. #define ISALPHA(c) (isascii (c) && isalpha (c))
  126. #define ISCNTRL(c) (isascii (c) && iscntrl (c))
  127. #define ISLOWER(c) (isascii (c) && islower (c))
  128. #define ISPUNCT(c) (isascii (c) && ispunct (c))
  129. #define ISSPACE(c) (isascii (c) && isspace (c))
  130. #define ISUPPER(c) (isascii (c) && isupper (c))
  131. #define ISXDIGIT(c) (isascii (c) && isxdigit (c))
  132.  
  133. #ifndef NULL
  134. #define NULL 0
  135. #endif
  136.  
  137. /* We remove any previous definition of `SIGN_EXTEND_CHAR',
  138.    since ours (we hope) works properly with all combinations of
  139.    machines, compilers, `char' and `unsigned char' argument types.
  140.    (Per Bothner suggested the basic approach.)  */
  141. #undef SIGN_EXTEND_CHAR
  142. #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
  143.  
  144. /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
  145.    use `alloca' instead of `malloc'.  This is because using malloc in
  146.    re_search* or re_match* could cause memory leaks when C-g is used in
  147.    Emacs; also, malloc is slower and causes storage fragmentation.  On
  148.    the other hand, malloc is more portable, and easier to debug.  
  149.    
  150.    Because we sometimes use alloca, some routines have to be macros,
  151.    not functions -- `alloca'-allocated space disappears at the end of the
  152.    function it is called in.  */
  153.  
  154. #ifdef REGEX_MALLOC
  155.  
  156. #define REGEX_ALLOCATE malloc
  157. #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
  158.  
  159. #else /* not REGEX_MALLOC  */
  160.  
  161. #define REGEX_ALLOCATE alloca
  162.  
  163. /* Assumes a `char *destination' variable.  */
  164. #define REGEX_REALLOCATE(source, osize, nsize)                \
  165.   (destination = (char *) alloca (nsize),                \
  166.    bcopy (source, destination, osize),                    \
  167.    destination)
  168.  
  169. #endif /* not REGEX_MALLOC */
  170.  
  171.  
  172. /* True if `size1' is non-NULL and PTR is pointing anywhere inside
  173.    `string1' or just past its end.  This works if PTR is NULL, which is
  174.    a good thing.  */
  175. #define FIRST_STRING_P(ptr)                     \
  176.   (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
  177.  
  178. /* (Re)Allocate N items of type T using malloc, or fail.  */
  179. #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
  180. #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
  181. #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
  182.  
  183. #define BYTEWIDTH 8 /* In bits.  */
  184.  
  185. #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
  186.  
  187. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  188. #define MIN(a, b) ((a) < (b) ? (a) : (b))
  189.  
  190. typedef char boolean;
  191. #define false 0
  192. #define true 1
  193.  
  194. /* These are the command codes that appear in compiled regular
  195.    expressions.  Some opcodes are followed by argument bytes.  A
  196.    command code can specify any interpretation whatsoever for its
  197.    arguments.  Zero bytes may appear in the compiled regular expression.
  198.  
  199.    The value of `exactn' is needed in search.c (search_buffer) in Emacs.
  200.    So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
  201.    `exactn' we use here must also be 1.  */
  202.  
  203. typedef enum
  204. {
  205.   no_op = 0,
  206.  
  207.         /* Followed by one byte giving n, then by n literal bytes.  */
  208.   exactn = 1,
  209.  
  210.         /* Matches any (more or less) character.  */
  211.   anychar,
  212.  
  213.         /* Matches any one char belonging to specified set.  First
  214.            following byte is number of bitmap bytes.  Then come bytes
  215.            for a bitmap saying which chars are in.  Bits in each byte
  216.            are ordered low-bit-first.  A character is in the set if its
  217.            bit is 1.  A character too large to have a bit in the map is
  218.            automatically not in the set.  */
  219.   charset,
  220.  
  221.         /* Same parameters as charset, but match any character that is
  222.            not one of those specified.  */
  223.   charset_not,
  224.  
  225.         /* Start remembering the text that is matched, for storing in a
  226.            register.  Followed by one byte with the register number, in
  227.            the range 0 to one less than the pattern buffer's re_nsub
  228.            field.  Then followed by one byte with the number of groups
  229.            inner to this one.  (This last has to be part of the
  230.            start_memory only because we need it in the on_failure_jump
  231.            of re_match_2.)  */
  232.   start_memory,
  233.  
  234.         /* Stop remembering the text that is matched and store it in a
  235.            memory register.  Followed by one byte with the register
  236.            number, in the range 0 to one less than `re_nsub' in the
  237.            pattern buffer, and one byte with the number of inner groups,
  238.            just like `start_memory'.  (We need the number of inner
  239.            groups here because we don't have any easy way of finding the
  240.            corresponding start_memory when we're at a stop_memory.)  */
  241.   stop_memory,
  242.  
  243.         /* Match a duplicate of something remembered. Followed by one
  244.            byte containing the register number.  */
  245.   duplicate,
  246.  
  247.         /* Fail unless at beginning of line.  */
  248.   begline,
  249.  
  250.         /* Fail unless at end of line.  */
  251.   endline,
  252.  
  253.         /* Succeeds if at beginning of buffer (if emacs) or at beginning
  254.            of string to be matched (if not).  */
  255.   begbuf,
  256.  
  257.         /* Analogously, for end of buffer/string.  */
  258.   endbuf,
  259.  
  260.         /* Followed by two byte relative address to which to jump.  */
  261.   jump, 
  262.  
  263.     /* Same as jump, but marks the end of an alternative.  */
  264.   jump_past_alt,
  265.  
  266.         /* Followed by two-byte relative address of place to resume at
  267.            in case of failure.  */
  268.   on_failure_jump,
  269.     
  270.         /* Like on_failure_jump, but pushes a placeholder instead of the
  271.            current string position when executed.  */
  272.   on_failure_keep_string_jump,
  273.   
  274.         /* Throw away latest failure point and then jump to following
  275.            two-byte relative address.  */
  276.   pop_failure_jump,
  277.  
  278.         /* Change to pop_failure_jump if know won't have to backtrack to
  279.            match; otherwise change to jump.  This is used to jump
  280.            back to the beginning of a repeat.  If what follows this jump
  281.            clearly won't match what the repeat does, such that we can be
  282.            sure that there is no use backtracking out of repetitions
  283.            already matched, then we change it to a pop_failure_jump.
  284.            Followed by two-byte address.  */
  285.   maybe_pop_jump,
  286.  
  287.         /* Jump to following two-byte address, and push a dummy failure
  288.            point. This failure point will be thrown away if an attempt
  289.            is made to use it for a failure.  A `+' construct makes this
  290.            before the first repeat.  Also used as an intermediary kind
  291.            of jump when compiling an alternative.  */
  292.   dummy_failure_jump,
  293.  
  294.     /* Push a dummy failure point and continue.  Used at the end of
  295.        alternatives.  */
  296.   push_dummy_failure,
  297.  
  298.         /* Followed by two-byte relative address and two-byte number n.
  299.            After matching N times, jump to the address upon failure.  */
  300.   succeed_n,
  301.  
  302.         /* Followed by two-byte relative address, and two-byte number n.
  303.            Jump to the address N times, then fail.  */
  304.   jump_n,
  305.  
  306.         /* Set the following two-byte relative address to the
  307.            subsequent two-byte number.  The address *includes* the two
  308.            bytes of number.  */
  309.   set_number_at,
  310.  
  311.   wordchar,    /* Matches any word-constituent character.  */
  312.   notwordchar,    /* Matches any char that is not a word-constituent.  */
  313.  
  314.   wordbeg,    /* Succeeds if at word beginning.  */
  315.   wordend,    /* Succeeds if at word end.  */
  316.  
  317.   wordbound,    /* Succeeds if at a word boundary.  */
  318.   notwordbound    /* Succeeds if not at a word boundary.  */
  319.  
  320. #ifdef emacs
  321.   ,before_dot,    /* Succeeds if before point.  */
  322.   at_dot,    /* Succeeds if at point.  */
  323.   after_dot,    /* Succeeds if after point.  */
  324.  
  325.     /* Matches any character whose syntax is specified.  Followed by
  326.            a byte which contains a syntax code, e.g., Sword.  */
  327.   syntaxspec,
  328.  
  329.     /* Matches any character whose syntax is not that specified.  */
  330.   notsyntaxspec
  331. #endif /* emacs */
  332. } re_opcode_t;
  333.  
  334. /* Common operations on the compiled pattern.  */
  335.  
  336. /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
  337.  
  338. #define STORE_NUMBER(destination, number)                \
  339.   do {                                    \
  340.     (destination)[0] = (number) & 0377;                    \
  341.     (destination)[1] = (number) >> 8;                    \
  342.   } while (0)
  343.  
  344. /* Same as STORE_NUMBER, except increment DESTINATION to
  345.    the byte after where the number is stored.  Therefore, DESTINATION
  346.    must be an lvalue.  */
  347.  
  348. #define STORE_NUMBER_AND_INCR(destination, number)            \
  349.   do {                                    \
  350.     STORE_NUMBER (destination, number);                    \
  351.     (destination) += 2;                            \
  352.   } while (0)
  353.  
  354. /* Put into DESTINATION a number stored in two contiguous bytes starting
  355.    at SOURCE.  */
  356.  
  357. #define EXTRACT_NUMBER(destination, source)                \
  358.   do {                                    \
  359.     (destination) = *(source) & 0377;                    \
  360.     (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;        \
  361.   } while (0)
  362.  
  363. #ifdef DEBUG
  364. static void
  365. extract_number (dest, source)
  366.     int *dest;
  367.     unsigned char *source;
  368. {
  369.   int temp = SIGN_EXTEND_CHAR (*(source + 1)); 
  370.   *dest = *source & 0377;
  371.   *dest += temp << 8;
  372. }
  373.  
  374. #ifndef EXTRACT_MACROS /* To debug the macros.  */
  375. #undef EXTRACT_NUMBER
  376. #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
  377. #endif /* not EXTRACT_MACROS */
  378.  
  379. #endif /* DEBUG */
  380.  
  381. /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
  382.    SOURCE must be an lvalue.  */
  383.  
  384. #define EXTRACT_NUMBER_AND_INCR(destination, source)            \
  385.   do {                                    \
  386.     EXTRACT_NUMBER (destination, source);                \
  387.     (source) += 2;                             \
  388.   } while (0)
  389.  
  390. #ifdef DEBUG
  391. static void
  392. extract_number_and_incr (destination, source)
  393.     int *destination;
  394.     unsigned char **source;
  395.   extract_number (destination, *source);
  396.   *source += 2;
  397. }
  398.  
  399. #ifndef EXTRACT_MACROS
  400. #undef EXTRACT_NUMBER_AND_INCR
  401. #define EXTRACT_NUMBER_AND_INCR(dest, src) \
  402.   extract_number_and_incr (&dest, &src)
  403. #endif /* not EXTRACT_MACROS */
  404.  
  405. #endif /* DEBUG */
  406.  
  407. /* If DEBUG is defined, Regex prints many voluminous messages about what
  408.    it is doing (if the variable `debug' is nonzero).  If linked with the
  409.    main program in `iregex.c', you can enter patterns and strings
  410.    interactively.  And if linked with the main program in `main.c' and
  411.    the other test files, you can run the already-written tests.  */
  412.  
  413. #ifdef DEBUG
  414.  
  415. /* We use standard I/O for debugging.  */
  416. #include <stdio.h>
  417.  
  418. /* It is useful to test things that ``must'' be true when debugging.  */
  419. #include <assert.h>
  420.  
  421. static int debug = 0;
  422.  
  423. #define DEBUG_STATEMENT(e) e
  424. #define DEBUG_PRINT1(x) if (debug) printf (x)
  425. #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
  426. #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
  427. #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
  428. #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)                 \
  429.   if (debug) print_partial_compiled_pattern (s, e)
  430. #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)            \
  431.   if (debug) print_double_string (w, s1, sz1, s2, sz2)
  432.  
  433.  
  434. extern void printchar ();
  435.  
  436. /* Print the fastmap in human-readable form.  */
  437.  
  438. void
  439. print_fastmap (fastmap)
  440.     char *fastmap;
  441. {
  442.   unsigned was_a_range = 0;
  443.   unsigned i = 0;  
  444.   
  445.   while (i < (1 << BYTEWIDTH))
  446.     {
  447.       if (fastmap[i++])
  448.     {
  449.       was_a_range = 0;
  450.           printchar (i - 1);
  451.           while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
  452.             {
  453.               was_a_range = 1;
  454.               i++;
  455.             }
  456.       if (was_a_range)
  457.             {
  458.               printf ("-");
  459.               printchar (i - 1);
  460.             }
  461.         }
  462.     }
  463.   putchar ('\n'); 
  464. }
  465.  
  466.  
  467. /* Print a compiled pattern string in human-readable form, starting at
  468.    the START pointer into it and ending just before the pointer END.  */
  469.  
  470. void
  471. print_partial_compiled_pattern (start, end)
  472.     unsigned char *start;
  473.     unsigned char *end;
  474. {
  475.   int mcnt, mcnt2;
  476.   unsigned char *p = start;
  477.   unsigned char *pend = end;
  478.  
  479.   if (start == NULL)
  480.     {
  481.       printf ("(null)\n");
  482.       return;
  483.     }
  484.     
  485.   /* Loop over pattern commands.  */
  486.   while (p < pend)
  487.     {
  488.       printf ("%d:\t", p - start);
  489.  
  490.       switch ((re_opcode_t) *p++)
  491.     {
  492.         case no_op:
  493.           printf ("/no_op");
  494.           break;
  495.  
  496.     case exactn:
  497.       mcnt = *p++;
  498.           printf ("/exactn/%d", mcnt);
  499.           do
  500.         {
  501.               putchar ('/');
  502.           printchar (*p++);
  503.             }
  504.           while (--mcnt);
  505.           break;
  506.  
  507.     case start_memory:
  508.           mcnt = *p++;
  509.           printf ("/start_memory/%d/%d", mcnt, *p++);
  510.           break;
  511.  
  512.     case stop_memory:
  513.           mcnt = *p++;
  514.       printf ("/stop_memory/%d/%d", mcnt, *p++);
  515.           break;
  516.  
  517.     case duplicate:
  518.       printf ("/duplicate/%d", *p++);
  519.       break;
  520.  
  521.     case anychar:
  522.       printf ("/anychar");
  523.       break;
  524.  
  525.     case charset:
  526.         case charset_not:
  527.           {
  528.             register int c, last = -100;
  529.         register int in_range = 0;
  530.  
  531.         printf ("/charset [%s",
  532.                 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
  533.             
  534.             assert (p + *p < pend);
  535.  
  536.             for (c = 0; c < 256; c++)
  537.           if (c / 8 < *p
  538.           && (p[1 + (c/8)] & (1 << (c % 8))))
  539.         {
  540.           /* Are we starting a range?  */
  541.           if (last + 1 == c && ! in_range)
  542.             {
  543.               putchar ('-');
  544.               in_range = 1;
  545.             }
  546.           /* Have we broken a range?  */
  547.           else if (last + 1 != c && in_range)
  548.               {
  549.               printchar (last);
  550.               in_range = 0;
  551.             }
  552.                 
  553.           if (! in_range)
  554.             printchar (c);
  555.  
  556.           last = c;
  557.               }
  558.  
  559.         if (in_range)
  560.           printchar (last);
  561.  
  562.         putchar (']');
  563.  
  564.         p += 1 + *p;
  565.       }
  566.       break;
  567.  
  568.     case begline:
  569.       printf ("/begline");
  570.           break;
  571.  
  572.     case endline:
  573.           printf ("/endline");
  574.           break;
  575.  
  576.     case on_failure_jump:
  577.           extract_number_and_incr (&mcnt, &p);
  578.         printf ("/on_failure_jump to %d", p + mcnt - start);
  579.           break;
  580.  
  581.     case on_failure_keep_string_jump:
  582.           extract_number_and_incr (&mcnt, &p);
  583.         printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
  584.           break;
  585.  
  586.     case dummy_failure_jump:
  587.           extract_number_and_incr (&mcnt, &p);
  588.         printf ("/dummy_failure_jump to %d", p + mcnt - start);
  589.           break;
  590.  
  591.     case push_dummy_failure:
  592.           printf ("/push_dummy_failure");
  593.           break;
  594.           
  595.         case maybe_pop_jump:
  596.           extract_number_and_incr (&mcnt, &p);
  597.         printf ("/maybe_pop_jump to %d", p + mcnt - start);
  598.       break;
  599.  
  600.         case pop_failure_jump:
  601.       extract_number_and_incr (&mcnt, &p);
  602.         printf ("/pop_failure_jump to %d", p + mcnt - start);
  603.       break;          
  604.           
  605.         case jump_past_alt:
  606.       extract_number_and_incr (&mcnt, &p);
  607.         printf ("/jump_past_alt to %d", p + mcnt - start);
  608.       break;          
  609.           
  610.         case jump:
  611.       extract_number_and_incr (&mcnt, &p);
  612.         printf ("/jump to %d", p + mcnt - start);
  613.       break;
  614.  
  615.         case succeed_n: 
  616.           extract_number_and_incr (&mcnt, &p);
  617.           extract_number_and_incr (&mcnt2, &p);
  618.       printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
  619.           break;
  620.         
  621.         case jump_n: 
  622.           extract_number_and_incr (&mcnt, &p);
  623.           extract_number_and_incr (&mcnt2, &p);
  624.       printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
  625.           break;
  626.         
  627.         case set_number_at: 
  628.           extract_number_and_incr (&mcnt, &p);
  629.           extract_number_and_incr (&mcnt2, &p);
  630.       printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
  631.           break;
  632.         
  633.         case wordbound:
  634.       printf ("/wordbound");
  635.       break;
  636.  
  637.     case notwordbound:
  638.       printf ("/notwordbound");
  639.           break;
  640.  
  641.     case wordbeg:
  642.       printf ("/wordbeg");
  643.       break;
  644.           
  645.     case wordend:
  646.       printf ("/wordend");
  647.           
  648. #ifdef emacs
  649.     case before_dot:
  650.       printf ("/before_dot");
  651.           break;
  652.  
  653.     case at_dot:
  654.       printf ("/at_dot");
  655.           break;
  656.  
  657.     case after_dot:
  658.       printf ("/after_dot");
  659.           break;
  660.  
  661.     case syntaxspec:
  662.           printf ("/syntaxspec");
  663.       mcnt = *p++;
  664.       printf ("/%d", mcnt);
  665.           break;
  666.       
  667.     case notsyntaxspec:
  668.           printf ("/notsyntaxspec");
  669.       mcnt = *p++;
  670.       printf ("/%d", mcnt);
  671.       break;
  672. #endif /* emacs */
  673.  
  674.     case wordchar:
  675.       printf ("/wordchar");
  676.           break;
  677.       
  678.     case notwordchar:
  679.       printf ("/notwordchar");
  680.           break;
  681.  
  682.     case begbuf:
  683.       printf ("/begbuf");
  684.           break;
  685.  
  686.     case endbuf:
  687.       printf ("/endbuf");
  688.           break;
  689.  
  690.         default:
  691.           printf ("?%d", *(p-1));
  692.     }
  693.  
  694.       putchar ('\n');
  695.     }
  696.  
  697.   printf ("%d:\tend of pattern.\n", p - start);
  698. }
  699.  
  700.  
  701. void
  702. print_compiled_pattern (bufp)
  703.     struct re_pattern_buffer *bufp;
  704. {
  705.   unsigned char *buffer = bufp->buffer;
  706.  
  707.   print_partial_compiled_pattern (buffer, buffer + bufp->used);
  708.   printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
  709.  
  710.   if (bufp->fastmap_accurate && bufp->fastmap)
  711.     {
  712.       printf ("fastmap: ");
  713.       print_fastmap (bufp->fastmap);
  714.     }
  715.  
  716.   printf ("re_nsub: %d\t", bufp->re_nsub);
  717.   printf ("regs_alloc: %d\t", bufp->regs_allocated);
  718.   printf ("can_be_null: %d\t", bufp->can_be_null);
  719.   printf ("newline_anchor: %d\n", bufp->newline_anchor);
  720.   printf ("no_sub: %d\t", bufp->no_sub);
  721.   printf ("not_bol: %d\t", bufp->not_bol);
  722.   printf ("not_eol: %d\t", bufp->not_eol);
  723.   printf ("syntax: %d\n", bufp->syntax);
  724.   /* Perhaps we should print the translate table?  */
  725. }
  726.  
  727.  
  728. void
  729. print_double_string (where, string1, size1, string2, size2)
  730.     const char *where;
  731.     const char *string1;
  732.     const char *string2;
  733.     int size1;
  734.     int size2;
  735. {
  736.   unsigned this_char;
  737.   
  738.   if (where == NULL)
  739.     printf ("(null)");
  740.   else
  741.     {
  742.       if (FIRST_STRING_P (where))
  743.         {
  744.           for (this_char = where - string1; this_char < size1; this_char++)
  745.             printchar (string1[this_char]);
  746.  
  747.           where = string2;    
  748.         }
  749.  
  750.       for (this_char = where - string2; this_char < size2; this_char++)
  751.         printchar (string2[this_char]);
  752.     }
  753. }
  754.  
  755. #else /* not DEBUG */
  756.  
  757. #undef assert
  758. #define assert(e)
  759.  
  760. #define DEBUG_STATEMENT(e)
  761. #define DEBUG_PRINT1(x)
  762. #define DEBUG_PRINT2(x1, x2)
  763. #define DEBUG_PRINT3(x1, x2, x3)
  764. #define DEBUG_PRINT4(x1, x2, x3, x4)
  765. #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
  766. #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
  767.  
  768. #endif /* not DEBUG */
  769.  
  770. /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
  771.    also be assigned to arbitrarily: each pattern buffer stores its own
  772.    syntax, so it can be changed between regex compilations.  */
  773. reg_syntax_t re_syntax_options = RE_SYNTAX_EMACS;
  774.  
  775.  
  776. /* Specify the precise syntax of regexps for compilation.  This provides
  777.    for compatibility for various utilities which historically have
  778.    different, incompatible syntaxes.
  779.  
  780.    The argument SYNTAX is a bit mask comprised of the various bits
  781.    defined in regex.h.  We return the old syntax.  */
  782.  
  783. reg_syntax_t
  784. re_set_syntax (syntax)
  785.     reg_syntax_t syntax;
  786. {
  787.   reg_syntax_t ret = re_syntax_options;
  788.   
  789.   re_syntax_options = syntax;
  790.   return ret;
  791. }
  792.  
  793. /* This table gives an error message for each of the error codes listed
  794.    in regex.h.  Obviously the order here has to be same as there.  */
  795.  
  796. static const char *re_error_msg[] =
  797.   { NULL,                    /* REG_NOERROR */
  798.     "No match",                    /* REG_NOMATCH */
  799.     "Invalid regular expression",        /* REG_BADPAT */
  800.     "Invalid collation character",        /* REG_ECOLLATE */
  801.     "Invalid character class name",        /* REG_ECTYPE */
  802.     "Trailing backslash",            /* REG_EESCAPE */
  803.     "Invalid back reference",            /* REG_ESUBREG */
  804.     "Unmatched [ or [^",            /* REG_EBRACK */
  805.     "Unmatched ( or \\(",            /* REG_EPAREN */
  806.     "Unmatched \\{",                /* REG_EBRACE */
  807.     "Invalid content of \\{\\}",        /* REG_BADBR */
  808.     "Invalid range end",            /* REG_ERANGE */
  809.     "Memory exhausted",                /* REG_ESPACE */
  810.     "Invalid preceding regular expression",    /* REG_BADRPT */
  811.     "Premature end of regular expression",    /* REG_EEND */
  812.     "Regular expression too big",        /* REG_ESIZE */
  813.     "Unmatched ) or \\)",            /* REG_ERPAREN */
  814.   };
  815.  
  816. /* Subroutine declarations and macros for regex_compile.  */
  817.  
  818. static void store_op1 (), store_op2 ();
  819. static void
  820. insert_op1 (
  821.     re_opcode_t op,
  822.     unsigned char *loc,
  823.     int arg,
  824.     unsigned char *end);
  825. static void
  826. insert_op2 (
  827.     re_opcode_t op,
  828.     unsigned char *loc,
  829.     int arg1, int arg2,
  830.     unsigned char *end);
  831. static void
  832. store_op1 (
  833.     re_opcode_t op,
  834.     unsigned char *loc,
  835.     int arg);
  836. static void
  837. store_op2 (
  838.     re_opcode_t op,
  839.     unsigned char *loc,
  840.     int arg1, int arg2);
  841. static boolean
  842. at_begline_loc_p (
  843.     const char *pattern, const char *p,
  844.     reg_syntax_t syntax);
  845. static boolean
  846. at_endline_loc_p (
  847.     const char *p, const char *pend,
  848.     int syntax);
  849. static reg_errcode_t
  850. compile_range (
  851.     const char **p_ptr, const char *pend,
  852.     char *translate,
  853.     reg_syntax_t syntax,
  854.     unsigned char *b);
  855.  
  856.  
  857. /* Fetch the next character in the uncompiled pattern---translating it 
  858.    if necessary.  Also cast from a signed character in the constant
  859.    string passed to us by the user to an unsigned char that we can use
  860.    as an array index (in, e.g., `translate').  */
  861. #define PATFETCH(c)                            \
  862.   do {if (p == pend) return REG_EEND;                    \
  863.     c = (unsigned char) *p++;                        \
  864.     if (translate) c = translate[c];                     \
  865.   } while (0)
  866.  
  867. /* Fetch the next character in the uncompiled pattern, with no
  868.    translation.  */
  869. #define PATFETCH_RAW(c)                            \
  870.   do {if (p == pend) return REG_EEND;                    \
  871.     c = (unsigned char) *p++;                         \
  872.   } while (0)
  873.  
  874. /* Go backwards one character in the pattern.  */
  875. #define PATUNFETCH p--
  876.  
  877.  
  878. /* If `translate' is non-null, return translate[D], else just D.  We
  879.    cast the subscript to translate because some data is declared as
  880.    `char *', to avoid warnings when a string constant is passed.  But
  881.    when we use a character as a subscript we must make it unsigned.  */
  882. #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
  883.  
  884.  
  885. /* Macros for outputting the compiled pattern into `buffer'.  */
  886.  
  887. /* If the buffer isn't allocated when it comes in, use this.  */
  888. #define INIT_BUF_SIZE  32
  889.  
  890. /* Make sure we have at least N more bytes of space in buffer.  */
  891. #define GET_BUFFER_SPACE(n)                        \
  892.     while (b - bufp->buffer + (n) > bufp->allocated)            \
  893.       EXTEND_BUFFER ()
  894.  
  895. /* Make sure we have one more byte of buffer space and then add C to it.  */
  896. #define BUF_PUSH(c)                            \
  897.   do {                                    \
  898.     GET_BUFFER_SPACE (1);                        \
  899.     *b++ = (unsigned char) (c);                        \
  900.   } while (0)
  901.  
  902.  
  903. /* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
  904. #define BUF_PUSH_2(c1, c2)                        \
  905.   do {                                    \
  906.     GET_BUFFER_SPACE (2);                        \
  907.     *b++ = (unsigned char) (c1);                    \
  908.     *b++ = (unsigned char) (c2);                    \
  909.   } while (0)
  910.  
  911.  
  912. /* As with BUF_PUSH_2, except for three bytes.  */
  913. #define BUF_PUSH_3(c1, c2, c3)                        \
  914.   do {                                    \
  915.     GET_BUFFER_SPACE (3);                        \
  916.     *b++ = (unsigned char) (c1);                    \
  917.     *b++ = (unsigned char) (c2);                    \
  918.     *b++ = (unsigned char) (c3);                    \
  919.   } while (0)
  920.  
  921.  
  922. /* Store a jump with opcode OP at LOC to location TO.  We store a
  923.    relative address offset by the three bytes the jump itself occupies.  */
  924. #define STORE_JUMP(op, loc, to) \
  925.   store_op1 (op, loc, (to) - (loc) - 3)
  926.  
  927. /* Likewise, for a two-argument jump.  */
  928. #define STORE_JUMP2(op, loc, to, arg) \
  929.   store_op2 (op, loc, (to) - (loc) - 3, arg)
  930.  
  931. /* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
  932. #define INSERT_JUMP(op, loc, to) \
  933.   insert_op1 (op, loc, (to) - (loc) - 3, b)
  934.  
  935. /* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
  936. #define INSERT_JUMP2(op, loc, to, arg) \
  937.   insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
  938.  
  939.  
  940. /* This is not an arbitrary limit: the arguments which represent offsets
  941.    into the pattern are two bytes long.  So if 2^16 bytes turns out to
  942.    be too small, many things would have to change.  */
  943. #define MAX_BUF_SIZE (1L << 16)
  944.  
  945.  
  946. /* Extend the buffer by twice its current size via realloc and
  947.    reset the pointers that pointed into the old block to point to the
  948.    correct places in the new one.  If extending the buffer results in it
  949.    being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
  950. #define EXTEND_BUFFER()                            \
  951.   do {                                     \
  952.     unsigned char *old_buffer = bufp->buffer;                \
  953.     if (bufp->allocated == MAX_BUF_SIZE)                 \
  954.       return REG_ESIZE;                            \
  955.     bufp->allocated <<= 1;                        \
  956.     if (bufp->allocated > MAX_BUF_SIZE)                    \
  957.       bufp->allocated = MAX_BUF_SIZE;                     \
  958.     bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
  959.     if (bufp->buffer == NULL)                        \
  960.       return REG_ESPACE;                        \
  961.     /* If the buffer moved, move all the pointers into it.  */        \
  962.     if (old_buffer != bufp->buffer)                    \
  963.       {                                    \
  964.         b = (b - old_buffer) + bufp->buffer;                \
  965.         begalt = (begalt - old_buffer) + bufp->buffer;            \
  966.         if (fixup_alt_jump)                        \
  967.           fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
  968.         if (laststart)                            \
  969.           laststart = (laststart - old_buffer) + bufp->buffer;        \
  970.         if (pending_exact)                        \
  971.           pending_exact = (pending_exact - old_buffer) + bufp->buffer;    \
  972.       }                                    \
  973.   } while (0)
  974.  
  975.  
  976. /* Since we have one byte reserved for the register number argument to
  977.    {start,stop}_memory, the maximum number of groups we can report
  978.    things about is what fits in that byte.  */
  979. #define MAX_REGNUM 255
  980.  
  981. /* But patterns can have more than `MAX_REGNUM' registers.  We just
  982.    ignore the excess.  */
  983. typedef unsigned regnum_t;
  984.  
  985.  
  986. /* Macros for the compile stack.  */
  987.  
  988. /* Since offsets can go either forwards or backwards, this type needs to
  989.    be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
  990. typedef int pattern_offset_t;
  991.  
  992. typedef struct
  993. {
  994.   pattern_offset_t begalt_offset;
  995.   pattern_offset_t fixup_alt_jump;
  996.   pattern_offset_t inner_group_offset;
  997.   pattern_offset_t laststart_offset;  
  998.   regnum_t regnum;
  999. } compile_stack_elt_t;
  1000.  
  1001.  
  1002. typedef struct
  1003. {
  1004.   compile_stack_elt_t *stack;
  1005.   unsigned size;
  1006.   unsigned avail;            /* Offset of next open position.  */
  1007. } compile_stack_type;
  1008.  
  1009. static boolean group_in_compile_stack (
  1010.     compile_stack_type compile_stack,
  1011.     regnum_t regnum);
  1012.  
  1013.  
  1014. #define INIT_COMPILE_STACK_SIZE 32
  1015.  
  1016. #define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
  1017. #define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
  1018.  
  1019. /* The next available element.  */
  1020. #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
  1021.  
  1022.  
  1023. /* Set the bit for character C in a list.  */
  1024. #define SET_LIST_BIT(c)                               \
  1025.   (b[((unsigned char) (c)) / BYTEWIDTH]               \
  1026.    |= 1 << (((unsigned char) c) % BYTEWIDTH))
  1027.  
  1028.  
  1029. /* Get the next unsigned number in the uncompiled pattern.  */
  1030. #define GET_UNSIGNED_NUMBER(num)                     \
  1031.   { if (p != pend)                            \
  1032.      {                                    \
  1033.        PATFETCH (c);                             \
  1034.        while (ISDIGIT (c))                         \
  1035.          {                                 \
  1036.            if (num < 0)                            \
  1037.               num = 0;                            \
  1038.            num = num * 10 + c - '0';                     \
  1039.            if (p == pend)                         \
  1040.               break;                             \
  1041.            PATFETCH (c);                        \
  1042.          }                                 \
  1043.        }                                 \
  1044.     }        
  1045.  
  1046. #define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
  1047.  
  1048. #define IS_CHAR_CLASS(string)                        \
  1049.    (STREQ (string, "alpha") || STREQ (string, "upper")            \
  1050.     || STREQ (string, "lower") || STREQ (string, "digit")        \
  1051.     || STREQ (string, "alnum") || STREQ (string, "xdigit")        \
  1052.     || STREQ (string, "space") || STREQ (string, "print")        \
  1053.     || STREQ (string, "punct") || STREQ (string, "graph")        \
  1054.     || STREQ (string, "cntrl") || STREQ (string, "blank"))
  1055.  
  1056. /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
  1057.    Returns one of error codes defined in `regex.h', or zero for success.
  1058.  
  1059.    Assumes the `allocated' (and perhaps `buffer') and `translate'
  1060.    fields are set in BUFP on entry.
  1061.  
  1062.    If it succeeds, results are put in BUFP (if it returns an error, the
  1063.    contents of BUFP are undefined):
  1064.      `buffer' is the compiled pattern;
  1065.      `syntax' is set to SYNTAX;
  1066.      `used' is set to the length of the compiled pattern;
  1067.      `fastmap_accurate' is zero;
  1068.      `re_nsub' is the number of subexpressions in PATTERN;
  1069.      `not_bol' and `not_eol' are zero;
  1070.    
  1071.    The `fastmap' and `newline_anchor' fields are neither
  1072.    examined nor set.  */
  1073.  
  1074. static reg_errcode_t
  1075. regex_compile (
  1076.      const char *pattern,
  1077.      int size,
  1078.      reg_syntax_t syntax,
  1079.      struct re_pattern_buffer *bufp)
  1080. {
  1081.   /* We fetch characters from PATTERN here.  Even though PATTERN is
  1082.      `char *' (i.e., signed), we declare these variables as unsigned, so
  1083.      they can be reliably used as array indices.  */
  1084.   register unsigned char c, c1;
  1085.   
  1086.   /* A random tempory spot in PATTERN.  */
  1087.   const char *p1;
  1088.  
  1089.   /* Points to the end of the buffer, where we should append.  */
  1090.   register unsigned char *b;
  1091.   
  1092.   /* Keeps track of unclosed groups.  */
  1093.   compile_stack_type compile_stack;
  1094.  
  1095.   /* Points to the current (ending) position in the pattern.  */
  1096.   const char *p = pattern;
  1097.   const char *pend = pattern + size;
  1098.   
  1099.   /* How to translate the characters in the pattern.  */
  1100.   char *translate = bufp->translate;
  1101.  
  1102.   /* Address of the count-byte of the most recently inserted `exactn'
  1103.      command.  This makes it possible to tell if a new exact-match
  1104.      character can be added to that command or if the character requires
  1105.      a new `exactn' command.  */
  1106.   unsigned char *pending_exact = 0;
  1107.  
  1108.   /* Address of start of the most recently finished expression.
  1109.      This tells, e.g., postfix * where to find the start of its
  1110.      operand.  Reset at the beginning of groups and alternatives.  */
  1111.   unsigned char *laststart = 0;
  1112.  
  1113.   /* Address of beginning of regexp, or inside of last group.  */
  1114.   unsigned char *begalt;
  1115.  
  1116.   /* Place in the uncompiled pattern (i.e., the {) to
  1117.      which to go back if the interval is invalid.  */
  1118.   const char *beg_interval;
  1119.                 
  1120.   /* Address of the place where a forward jump should go to the end of
  1121.      the containing expression.  Each alternative of an `or' -- except the
  1122.      last -- ends with a forward jump of this sort.  */
  1123.   unsigned char *fixup_alt_jump = 0;
  1124.  
  1125.   /* Counts open-groups as they are encountered.  Remembered for the
  1126.      matching close-group on the compile stack, so the same register
  1127.      number is put in the stop_memory as the start_memory.  */
  1128.   regnum_t regnum = 0;
  1129.  
  1130. #ifdef DEBUG
  1131.   DEBUG_PRINT1 ("\nCompiling pattern: ");
  1132.   if (debug)
  1133.     {
  1134.       unsigned debug_count;
  1135.       
  1136.       for (debug_count = 0; debug_count < size; debug_count++)
  1137.         printchar (pattern[debug_count]);
  1138.       putchar ('\n');
  1139.     }
  1140. #endif /* DEBUG */
  1141.  
  1142.   /* Initialize the compile stack.  */
  1143.   compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
  1144.   if (compile_stack.stack == NULL)
  1145.     return REG_ESPACE;
  1146.  
  1147.   compile_stack.size = INIT_COMPILE_STACK_SIZE;
  1148.   compile_stack.avail = 0;
  1149.  
  1150.   /* Initialize the pattern buffer.  */
  1151.   bufp->syntax = syntax;
  1152.   bufp->fastmap_accurate = 0;
  1153.   bufp->not_bol = bufp->not_eol = 0;
  1154.  
  1155.   /* Set `used' to zero, so that if we return an error, the pattern
  1156.      printer (for debugging) will think there's no pattern.  We reset it
  1157.      at the end.  */
  1158.   bufp->used = 0;
  1159.   
  1160.   /* Always count groups, whether or not bufp->no_sub is set.  */
  1161.   bufp->re_nsub = 0;                
  1162.  
  1163. #if !defined (emacs) && !defined (SYNTAX_TABLE)
  1164.   /* Initialize the syntax table.  */
  1165.    init_syntax_once ();
  1166. #endif
  1167.  
  1168.   if (bufp->allocated == 0)
  1169.     {
  1170.       if (bufp->buffer)
  1171.     { /* If zero allocated, but buffer is non-null, try to realloc
  1172.              enough space.  This loses if buffer's address is bogus, but
  1173.              that is the user's responsibility.  */
  1174.           RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
  1175.         }
  1176.       else
  1177.         { /* Caller did not allocate a buffer.  Do it for them.  */
  1178.           bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
  1179.         }
  1180.       if (!bufp->buffer) return REG_ESPACE;
  1181.  
  1182.       bufp->allocated = INIT_BUF_SIZE;
  1183.     }
  1184.  
  1185.   begalt = b = bufp->buffer;
  1186.  
  1187.   /* Loop through the uncompiled pattern until we're at the end.  */
  1188.   while (p != pend)
  1189.     {
  1190.       PATFETCH (c);
  1191.  
  1192.       switch (c)
  1193.         {
  1194.         case '^':
  1195.           {
  1196.             if (   /* If at start of pattern, it's an operator.  */
  1197.                    p == pattern + 1
  1198.                    /* If context independent, it's an operator.  */
  1199.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  1200.                    /* Otherwise, depends on what's come before.  */
  1201.                 || at_begline_loc_p (pattern, p, syntax))
  1202.               BUF_PUSH (begline);
  1203.             else
  1204.               goto normal_char;
  1205.           }
  1206.           break;
  1207.  
  1208.  
  1209.         case '$':
  1210.           {
  1211.             if (   /* If at end of pattern, it's an operator.  */
  1212.                    p == pend 
  1213.                    /* If context independent, it's an operator.  */
  1214.                 || syntax & RE_CONTEXT_INDEP_ANCHORS
  1215.                    /* Otherwise, depends on what's next.  */
  1216.                 || at_endline_loc_p (p, pend, syntax))
  1217.                BUF_PUSH (endline);
  1218.              else
  1219.                goto normal_char;
  1220.            }
  1221.            break;
  1222.  
  1223.  
  1224.     case '+':
  1225.         case '?':
  1226.           if ((syntax & RE_BK_PLUS_QM)
  1227.               || (syntax & RE_LIMITED_OPS))
  1228.             goto normal_char;
  1229.         handle_plus:
  1230.         case '*':
  1231.           /* If there is no previous pattern... */
  1232.           if (!laststart)
  1233.             {
  1234.               if (syntax & RE_CONTEXT_INVALID_OPS)
  1235.                 return REG_BADRPT;
  1236.               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
  1237.                 goto normal_char;
  1238.             }
  1239.  
  1240.           {
  1241.             /* Are we optimizing this jump?  */
  1242.             boolean keep_string_p = false;
  1243.             
  1244.             /* 1 means zero (many) matches is allowed.  */
  1245.             char zero_times_ok = 0, many_times_ok = 0;
  1246.  
  1247.             /* If there is a sequence of repetition chars, collapse it
  1248.                down to just one (the right one).  We can't combine
  1249.                interval operators with these because of, e.g., `a{2}*',
  1250.                which should only match an even number of `a's.  */
  1251.  
  1252.             for (;;)
  1253.               {
  1254.                 zero_times_ok |= c != '+';
  1255.                 many_times_ok |= c != '?';
  1256.  
  1257.                 if (p == pend)
  1258.                   break;
  1259.  
  1260.                 PATFETCH (c);
  1261.  
  1262.                 if (c == '*'
  1263.                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
  1264.                   ;
  1265.  
  1266.                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
  1267.                   {
  1268.                     if (p == pend) return REG_EESCAPE;
  1269.  
  1270.                     PATFETCH (c1);
  1271.                     if (!(c1 == '+' || c1 == '?'))
  1272.                       {
  1273.                         PATUNFETCH;
  1274.                         PATUNFETCH;
  1275.                         break;
  1276.                       }
  1277.  
  1278.                     c = c1;
  1279.                   }
  1280.                 else
  1281.                   {
  1282.                     PATUNFETCH;
  1283.                     break;
  1284.                   }
  1285.  
  1286.                 /* If we get here, we found another repeat character.  */
  1287.                }
  1288.  
  1289.             /* Star, etc. applied to an empty pattern is equivalent
  1290.                to an empty pattern.  */
  1291.             if (!laststart)  
  1292.               break;
  1293.  
  1294.             /* Now we know whether or not zero matches is allowed
  1295.                and also whether or not two or more matches is allowed.  */
  1296.             if (many_times_ok)
  1297.               { /* More than one repetition is allowed, so put in at the
  1298.                    end a backward relative jump from `b' to before the next
  1299.                    jump we're going to put in below (which jumps from
  1300.                    laststart to after this jump).  
  1301.  
  1302.                    But if we are at the `*' in the exact sequence `.*\n',
  1303.                    insert an unconditional jump backwards to the .,
  1304.                    instead of the beginning of the loop.  This way we only
  1305.                    push a failure point once, instead of every time
  1306.                    through the loop.  */
  1307.                 assert (p - 1 > pattern);
  1308.  
  1309.                 /* Allocate the space for the jump.  */
  1310.                 GET_BUFFER_SPACE (3);
  1311.  
  1312.                 /* We know we are not at the first character of the pattern,
  1313.                    because laststart was nonzero.  And we've already
  1314.                    incremented `p', by the way, to be the character after
  1315.                    the `*'.  Do we have to do something analogous here
  1316.                    for null bytes, because of RE_DOT_NOT_NULL?  */
  1317.                 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
  1318.             && zero_times_ok
  1319.                     && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
  1320.                     && !(syntax & RE_DOT_NEWLINE))
  1321.                   { /* We have .*\n.  */
  1322.                     STORE_JUMP (jump, b, laststart);
  1323.                     keep_string_p = true;
  1324.                   }
  1325.                 else
  1326.                   /* Anything else.  */
  1327.                   STORE_JUMP (maybe_pop_jump, b, laststart - 3);
  1328.  
  1329.                 /* We've added more stuff to the buffer.  */
  1330.                 b += 3;
  1331.               }
  1332.  
  1333.             /* On failure, jump from laststart to b + 3, which will be the
  1334.                end of the buffer after this jump is inserted.  */
  1335.             GET_BUFFER_SPACE (3);
  1336.             INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
  1337.                                        : on_failure_jump,
  1338.                          laststart, b + 3);
  1339.             pending_exact = 0;
  1340.             b += 3;
  1341.  
  1342.             if (!zero_times_ok)
  1343.               {
  1344.                 /* At least one repetition is required, so insert a
  1345.                    `dummy_failure_jump' before the initial
  1346.                    `on_failure_jump' instruction of the loop. This
  1347.                    effects a skip over that instruction the first time
  1348.                    we hit that loop.  */
  1349.                 GET_BUFFER_SPACE (3);
  1350.                 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
  1351.                 b += 3;
  1352.               }
  1353.             }
  1354.       break;
  1355.  
  1356.  
  1357.     case '.':
  1358.           laststart = b;
  1359.           BUF_PUSH (anychar);
  1360.           break;
  1361.  
  1362.  
  1363.         case '[':
  1364.           {
  1365.             boolean had_char_class = false;
  1366.  
  1367.             if (p == pend) return REG_EBRACK;
  1368.  
  1369.             /* Ensure that we have enough space to push a charset: the
  1370.                opcode, the length count, and the bitset; 34 bytes in all.  */
  1371.         GET_BUFFER_SPACE (34);
  1372.  
  1373.             laststart = b;
  1374.  
  1375.             /* We test `*p == '^' twice, instead of using an if
  1376.                statement, so we only need one BUF_PUSH.  */
  1377.             BUF_PUSH (*p == '^' ? charset_not : charset); 
  1378.             if (*p == '^')
  1379.               p++;
  1380.  
  1381.             /* Remember the first position in the bracket expression.  */
  1382.             p1 = p;
  1383.  
  1384.             /* Push the number of bytes in the bitmap.  */
  1385.             BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
  1386.  
  1387.             /* Clear the whole map.  */
  1388.             bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
  1389.  
  1390.             /* charset_not matches newline according to a syntax bit.  */
  1391.             if ((re_opcode_t) b[-2] == charset_not
  1392.                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
  1393.               SET_LIST_BIT ('\n');
  1394.  
  1395.             /* Read in characters and ranges, setting map bits.  */
  1396.             for (;;)
  1397.               {
  1398.                 if (p == pend) return REG_EBRACK;
  1399.  
  1400.                 PATFETCH (c);
  1401.  
  1402.                 /* \ might escape characters inside [...] and [^...].  */
  1403.                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
  1404.                   {
  1405.                     if (p == pend) return REG_EESCAPE;
  1406.  
  1407.                     PATFETCH (c1);
  1408.                     SET_LIST_BIT (c1);
  1409.                     continue;
  1410.                   }
  1411.  
  1412.                 /* Could be the end of the bracket expression.  If it's
  1413.                    not (i.e., when the bracket expression is `[]' so
  1414.                    far), the ']' character bit gets set way below.  */
  1415.                 if (c == ']' && p != p1 + 1)
  1416.                   break;
  1417.  
  1418.                 /* Look ahead to see if it's a range when the last thing
  1419.                    was a character class.  */
  1420.                 if (had_char_class && c == '-' && *p != ']')
  1421.                   return REG_ERANGE;
  1422.  
  1423.                 /* Look ahead to see if it's a range when the last thing
  1424.                    was a character: if this is a hyphen not at the
  1425.                    beginning or the end of a list, then it's the range
  1426.                    operator.  */
  1427.                 if (c == '-' 
  1428.                     && !(p - 2 >= pattern && p[-2] == '[') 
  1429.                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
  1430.                     && *p != ']')
  1431.                   {
  1432.                     reg_errcode_t ret
  1433.                       = compile_range (&p, pend, translate, syntax, b);
  1434.                     if (ret != REG_NOERROR) return ret;
  1435.                   }
  1436.  
  1437.                 else if (p[0] == '-' && p[1] != ']')
  1438.                   { /* This handles ranges made up of characters only.  */
  1439.                     reg_errcode_t ret;
  1440.  
  1441.             /* Move past the `-'.  */
  1442.                     PATFETCH (c1);
  1443.                     
  1444.                     ret = compile_range (&p, pend, translate, syntax, b);
  1445.                     if (ret != REG_NOERROR) return ret;
  1446.                   }
  1447.  
  1448.                 /* See if we're at the beginning of a possible character
  1449.                    class.  */
  1450.  
  1451.                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
  1452.                   { /* Leave room for the null.  */
  1453.                     char str[CHAR_CLASS_MAX_LENGTH + 1];
  1454.  
  1455.                     PATFETCH (c);
  1456.                     c1 = 0;
  1457.  
  1458.                     /* If pattern is `[[:'.  */
  1459.                     if (p == pend) return REG_EBRACK;
  1460.  
  1461.                     for (;;)
  1462.                       {
  1463.                         PATFETCH (c);
  1464.                         if (c == ':' || c == ']' || p == pend
  1465.                             || c1 == CHAR_CLASS_MAX_LENGTH)
  1466.                           break;
  1467.                         str[c1++] = c;
  1468.                       }
  1469.                     str[c1] = '\0';
  1470.  
  1471.                     /* If isn't a word bracketed by `[:' and:`]':
  1472.                        undo the ending character, the letters, and leave 
  1473.                        the leading `:' and `[' (but set bits for them).  */
  1474.                     if (c == ':' && *p == ']')
  1475.                       {
  1476.                         int ch;
  1477.                         boolean is_alnum = STREQ (str, "alnum");
  1478.                         boolean is_alpha = STREQ (str, "alpha");
  1479.                         boolean is_blank = STREQ (str, "blank");
  1480.                         boolean is_cntrl = STREQ (str, "cntrl");
  1481.                         boolean is_digit = STREQ (str, "digit");
  1482.                         boolean is_graph = STREQ (str, "graph");
  1483.                         boolean is_lower = STREQ (str, "lower");
  1484.                         boolean is_print = STREQ (str, "print");
  1485.                         boolean is_punct = STREQ (str, "punct");
  1486.                         boolean is_space = STREQ (str, "space");
  1487.                         boolean is_upper = STREQ (str, "upper");
  1488.                         boolean is_xdigit = STREQ (str, "xdigit");
  1489.                         
  1490.                         if (!IS_CHAR_CLASS (str)) return REG_ECTYPE;
  1491.  
  1492.                         /* Throw away the ] at the end of the character
  1493.                            class.  */
  1494.                         PATFETCH (c);                    
  1495.  
  1496.                         if (p == pend) return REG_EBRACK;
  1497.  
  1498.                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
  1499.                           {
  1500.                             if (   (is_alnum  && ISALNUM (ch))
  1501.                                 || (is_alpha  && ISALPHA (ch))
  1502.                                 || (is_blank  && ISBLANK (ch))
  1503.                                 || (is_cntrl  && ISCNTRL (ch))
  1504.                                 || (is_digit  && ISDIGIT (ch))
  1505.                                 || (is_graph  && ISGRAPH (ch))
  1506.                                 || (is_lower  && ISLOWER (ch))
  1507.                                 || (is_print  && ISPRINT (ch))
  1508.                                 || (is_punct  && ISPUNCT (ch))
  1509.                                 || (is_space  && ISSPACE (ch))
  1510.                                 || (is_upper  && ISUPPER (ch))
  1511.                                 || (is_xdigit && ISXDIGIT (ch)))
  1512.                             SET_LIST_BIT (ch);
  1513.                           }
  1514.                         had_char_class = true;
  1515.                       }
  1516.                     else
  1517.                       {
  1518.                         c1++;
  1519.                         while (c1--)    
  1520.                           PATUNFETCH;
  1521.                         SET_LIST_BIT ('[');
  1522.                         SET_LIST_BIT (':');
  1523.                         had_char_class = false;
  1524.                       }
  1525.                   }
  1526.                 else
  1527.                   {
  1528.                     had_char_class = false;
  1529.                     SET_LIST_BIT (c);
  1530.                   }
  1531.               }
  1532.  
  1533.             /* Discard any (non)matching list bytes that are all 0 at the
  1534.                end of the map.  Decrease the map-length byte too.  */
  1535.             while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
  1536.               b[-1]--; 
  1537.             b += b[-1];
  1538.           }
  1539.           break;
  1540.  
  1541.  
  1542.     case '(':
  1543.           if (syntax & RE_NO_BK_PARENS)
  1544.             goto handle_open;
  1545.           else
  1546.             goto normal_char;
  1547.  
  1548.  
  1549.         case ')':
  1550.           if (syntax & RE_NO_BK_PARENS)
  1551.             goto handle_close;
  1552.           else
  1553.             goto normal_char;
  1554.  
  1555.  
  1556.         case '\n':
  1557.           if (syntax & RE_NEWLINE_ALT)
  1558.             goto handle_alt;
  1559.           else
  1560.             goto normal_char;
  1561.  
  1562.  
  1563.     case '|':
  1564.           if (syntax & RE_NO_BK_VBAR)
  1565.             goto handle_alt;
  1566.           else
  1567.             goto normal_char;
  1568.  
  1569.  
  1570.         case '{':
  1571.            if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
  1572.              goto handle_interval;
  1573.            else
  1574.              goto normal_char;
  1575.  
  1576.  
  1577.         case '\\':
  1578.           if (p == pend) return REG_EESCAPE;
  1579.  
  1580.           /* Do not translate the character after the \, so that we can
  1581.              distinguish, e.g., \B from \b, even if we normally would
  1582.              translate, e.g., B to b.  */
  1583.           PATFETCH_RAW (c);
  1584.  
  1585.           switch (c)
  1586.             {
  1587.             case '(':
  1588.               if (syntax & RE_NO_BK_PARENS)
  1589.                 goto normal_backslash;
  1590.  
  1591.             handle_open:
  1592.               bufp->re_nsub++;
  1593.               regnum++;
  1594.  
  1595.               if (COMPILE_STACK_FULL)
  1596.                 { 
  1597.                   RETALLOC (compile_stack.stack, compile_stack.size << 1,
  1598.                             compile_stack_elt_t);
  1599.                   if (compile_stack.stack == NULL) return REG_ESPACE;
  1600.  
  1601.                   compile_stack.size <<= 1;
  1602.                 }
  1603.  
  1604.               /* These are the values to restore when we hit end of this
  1605.                  group.  They are all relative offsets, so that if the
  1606.                  whole pattern moves because of realloc, they will still
  1607.                  be valid.  */
  1608.               COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
  1609.               COMPILE_STACK_TOP.fixup_alt_jump 
  1610.                 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
  1611.               COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
  1612.               COMPILE_STACK_TOP.regnum = regnum;
  1613.  
  1614.               /* We will eventually replace the 0 with the number of
  1615.                  groups inner to this one.  But do not push a
  1616.                  start_memory for groups beyond the last one we can
  1617.                  represent in the compiled pattern.  */
  1618.               if (regnum <= MAX_REGNUM)
  1619.                 {
  1620.                   COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
  1621.                   BUF_PUSH_3 (start_memory, regnum, 0);
  1622.                 }
  1623.                 
  1624.               compile_stack.avail++;
  1625.  
  1626.               fixup_alt_jump = 0;
  1627.               laststart = 0;
  1628.               begalt = b;
  1629.           /* If we've reached MAX_REGNUM groups, then this open
  1630.          won't actually generate any code, so we'll have to
  1631.          clear pending_exact explicitly.  */
  1632.           pending_exact = 0;
  1633.               break;
  1634.  
  1635.  
  1636.             case ')':
  1637.               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
  1638.  
  1639.               if (COMPILE_STACK_EMPTY)
  1640.                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1641.                   goto normal_backslash;
  1642.                 else
  1643.                   return REG_ERPAREN;
  1644.  
  1645.             handle_close:
  1646.               if (fixup_alt_jump)
  1647.                 { /* Push a dummy failure point at the end of the
  1648.                      alternative for a possible future
  1649.                      `pop_failure_jump' to pop.  See comments at
  1650.                      `push_dummy_failure' in `re_match_2'.  */
  1651.                   BUF_PUSH (push_dummy_failure);
  1652.                   
  1653.                   /* We allocated space for this jump when we assigned
  1654.                      to `fixup_alt_jump', in the `handle_alt' case below.  */
  1655.                   STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
  1656.                 }
  1657.  
  1658.               /* See similar code for backslashed left paren above.  */
  1659.               if (COMPILE_STACK_EMPTY)
  1660.                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
  1661.                   goto normal_char;
  1662.                 else
  1663.                   return REG_ERPAREN;
  1664.  
  1665.               /* Since we just checked for an empty stack above, this
  1666.                  ``can't happen''.  */
  1667.               assert (compile_stack.avail != 0);
  1668.               {
  1669.                 /* We don't just want to restore into `regnum', because
  1670.                    later groups should continue to be numbered higher,
  1671.                    as in `(ab)c(de)' -- the second group is #2.  */
  1672.                 regnum_t this_group_regnum;
  1673.  
  1674.                 compile_stack.avail--;        
  1675.                 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
  1676.                 fixup_alt_jump
  1677.                   = COMPILE_STACK_TOP.fixup_alt_jump
  1678.                     ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 
  1679.                     : 0;
  1680.                 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
  1681.                 this_group_regnum = COMPILE_STACK_TOP.regnum;
  1682.         /* If we've reached MAX_REGNUM groups, then this open
  1683.            won't actually generate any code, so we'll have to
  1684.            clear pending_exact explicitly.  */
  1685.         pending_exact = 0;
  1686.  
  1687.                 /* We're at the end of the group, so now we know how many
  1688.                    groups were inside this one.  */
  1689.                 if (this_group_regnum <= MAX_REGNUM)
  1690.                   {
  1691.                     unsigned char *inner_group_loc
  1692.                       = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
  1693.                     
  1694.                     *inner_group_loc = regnum - this_group_regnum;
  1695.                     BUF_PUSH_3 (stop_memory, this_group_regnum,
  1696.                                 regnum - this_group_regnum);
  1697.                   }
  1698.               }
  1699.               break;
  1700.  
  1701.  
  1702.             case '|':                    /* `\|'.  */
  1703.               if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
  1704.                 goto normal_backslash;
  1705.             handle_alt:
  1706.               if (syntax & RE_LIMITED_OPS)
  1707.                 goto normal_char;
  1708.  
  1709.               /* Insert before the previous alternative a jump which
  1710.                  jumps to this alternative if the former fails.  */
  1711.               GET_BUFFER_SPACE (3);
  1712.               INSERT_JUMP (on_failure_jump, begalt, b + 6);
  1713.               pending_exact = 0;
  1714.               b += 3;
  1715.  
  1716.               /* The alternative before this one has a jump after it
  1717.                  which gets executed if it gets matched.  Adjust that
  1718.                  jump so it will jump to this alternative's analogous
  1719.                  jump (put in below, which in turn will jump to the next
  1720.                  (if any) alternative's such jump, etc.).  The last such
  1721.                  jump jumps to the correct final destination.  A picture:
  1722.                           _____ _____ 
  1723.                           |   | |   |   
  1724.                           |   v |   v 
  1725.                          a | b   | c   
  1726.  
  1727.                  If we are at `b', then fixup_alt_jump right now points to a
  1728.                  three-byte space after `a'.  We'll put in the jump, set
  1729.                  fixup_alt_jump to right after `b', and leave behind three
  1730.                  bytes which we'll fill in when we get to after `c'.  */
  1731.  
  1732.               if (fixup_alt_jump)
  1733.                 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  1734.  
  1735.               /* Mark and leave space for a jump after this alternative,
  1736.                  to be filled in later either by next alternative or
  1737.                  when know we're at the end of a series of alternatives.  */
  1738.               fixup_alt_jump = b;
  1739.               GET_BUFFER_SPACE (3);
  1740.               b += 3;
  1741.  
  1742.               laststart = 0;
  1743.               begalt = b;
  1744.               break;
  1745.  
  1746.  
  1747.             case '{': 
  1748.               /* If \{ is a literal.  */
  1749.               if (!(syntax & RE_INTERVALS)
  1750.                      /* If we're at `\{' and it's not the open-interval 
  1751.                         operator.  */
  1752.                   || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
  1753.                   || (p - 2 == pattern  &&  p == pend))
  1754.                 goto normal_backslash;
  1755.  
  1756.             handle_interval:
  1757.               {
  1758.                 /* If got here, then the syntax allows intervals.  */
  1759.  
  1760.                 /* At least (most) this many matches must be made.  */
  1761.                 int lower_bound = -1, upper_bound = -1;
  1762.  
  1763.                 beg_interval = p - 1;
  1764.  
  1765.                 if (p == pend)
  1766.                   {
  1767.                     if (syntax & RE_NO_BK_BRACES)
  1768.                       goto unfetch_interval;
  1769.                     else
  1770.                       return REG_EBRACE;
  1771.                   }
  1772.  
  1773.                 GET_UNSIGNED_NUMBER (lower_bound);
  1774.  
  1775.                 if (c == ',')
  1776.                   {
  1777.                     GET_UNSIGNED_NUMBER (upper_bound);
  1778.                     if (upper_bound < 0) upper_bound = RE_DUP_MAX;
  1779.                   }
  1780.                 else
  1781.                   /* Interval such as `{1}' => match exactly once. */
  1782.                   upper_bound = lower_bound;
  1783.  
  1784.                 if (lower_bound < 0
  1785.                     || lower_bound > upper_bound)
  1786.                   {
  1787.                     if (syntax & RE_NO_BK_BRACES)
  1788.                       goto unfetch_interval;
  1789.                     else 
  1790.                       return REG_BADBR;
  1791.                   }
  1792.  
  1793.                 if (!(syntax & RE_NO_BK_BRACES)) 
  1794.                   {
  1795.                     if (c != '\\') return REG_EBRACE;
  1796.  
  1797.                     PATFETCH (c);
  1798.                   }
  1799.  
  1800.                 if (c != '}')
  1801.                   {
  1802.                     if (syntax & RE_NO_BK_BRACES)
  1803.                       goto unfetch_interval;
  1804.                     else 
  1805.                       return REG_BADBR;
  1806.                   }
  1807.  
  1808.                 /* We just parsed a valid interval.  */
  1809.  
  1810.                 /* If it's invalid to have no preceding re.  */
  1811.                 if (!laststart)
  1812.                   {
  1813.                     if (syntax & RE_CONTEXT_INVALID_OPS)
  1814.                       return REG_BADRPT;
  1815.                     else if (syntax & RE_CONTEXT_INDEP_OPS)
  1816.                       laststart = b;
  1817.                     else
  1818.                       goto unfetch_interval;
  1819.                   }
  1820.  
  1821.                 /* If the upper bound is zero, don't want to succeed at
  1822.                    all; jump from `laststart' to `b + 3', which will be
  1823.                    the end of the buffer after we insert the jump.  */
  1824.                  if (upper_bound == 0)
  1825.                    {
  1826.                      GET_BUFFER_SPACE (3);
  1827.                      INSERT_JUMP (jump, laststart, b + 3);
  1828.                      b += 3;
  1829.                    }
  1830.  
  1831.                  /* Otherwise, we have a nontrivial interval.  When
  1832.                     we're all done, the pattern will look like:
  1833.                       set_number_at <jump count> <upper bound>
  1834.                       set_number_at <succeed_n count> <lower bound>
  1835.                       succeed_n <after jump addr> <succed_n count>
  1836.                       <body of loop>
  1837.                       jump_n <succeed_n addr> <jump count>
  1838.                     (The upper bound and `jump_n' are omitted if
  1839.                     `upper_bound' is 1, though.)  */
  1840.                  else 
  1841.                    { /* If the upper bound is > 1, we need to insert
  1842.                         more at the end of the loop.  */
  1843.                      unsigned nbytes = 10 + (upper_bound > 1) * 10;
  1844.  
  1845.                      GET_BUFFER_SPACE (nbytes);
  1846.  
  1847.                      /* Initialize lower bound of the `succeed_n', even
  1848.                         though it will be set during matching by its
  1849.                         attendant `set_number_at' (inserted next),
  1850.                         because `re_compile_fastmap' needs to know.
  1851.                         Jump to the `jump_n' we might insert below.  */
  1852.                      INSERT_JUMP2 (succeed_n, laststart,
  1853.                                    b + 5 + (upper_bound > 1) * 5,
  1854.                                    lower_bound);
  1855.                      b += 5;
  1856.  
  1857.                      /* Code to initialize the lower bound.  Insert 
  1858.                         before the `succeed_n'.  The `5' is the last two
  1859.                         bytes of this `set_number_at', plus 3 bytes of
  1860.                         the following `succeed_n'.  */
  1861.                      insert_op2 (set_number_at, laststart, 5, lower_bound, b);
  1862.                      b += 5;
  1863.  
  1864.                      if (upper_bound > 1)
  1865.                        { /* More than one repetition is allowed, so
  1866.                             append a backward jump to the `succeed_n'
  1867.                             that starts this interval.
  1868.                             
  1869.                             When we've reached this during matching,
  1870.                             we'll have matched the interval once, so
  1871.                             jump back only `upper_bound - 1' times.  */
  1872.                          STORE_JUMP2 (jump_n, b, laststart + 5,
  1873.                                       upper_bound - 1);
  1874.                          b += 5;
  1875.  
  1876.                          /* The location we want to set is the second
  1877.                             parameter of the `jump_n'; that is `b-2' as
  1878.                             an absolute address.  `laststart' will be
  1879.                             the `set_number_at' we're about to insert;
  1880.                             `laststart+3' the number to set, the source
  1881.                             for the relative address.  But we are
  1882.                             inserting into the middle of the pattern --
  1883.                             so everything is getting moved up by 5.
  1884.                             Conclusion: (b - 2) - (laststart + 3) + 5,
  1885.                             i.e., b - laststart.
  1886.                             
  1887.                             We insert this at the beginning of the loop
  1888.                             so that if we fail during matching, we'll
  1889.                             reinitialize the bounds.  */
  1890.                          insert_op2 (set_number_at, laststart, b - laststart,
  1891.                                      upper_bound - 1, b);
  1892.                          b += 5;
  1893.                        }
  1894.                    }
  1895.                 pending_exact = 0;
  1896.                 beg_interval = NULL;
  1897.               }
  1898.               break;
  1899.  
  1900.             unfetch_interval:
  1901.               /* If an invalid interval, match the characters as literals.  */
  1902.                assert (beg_interval);
  1903.                p = beg_interval;
  1904.                beg_interval = NULL;
  1905.  
  1906.                /* normal_char and normal_backslash need `c'.  */
  1907.                PATFETCH (c);    
  1908.  
  1909.                if (!(syntax & RE_NO_BK_BRACES))
  1910.                  {
  1911.                    if (p > pattern  &&  p[-1] == '\\')
  1912.                      goto normal_backslash;
  1913.                  }
  1914.                goto normal_char;
  1915.  
  1916. #ifdef emacs
  1917.             /* There is no way to specify the before_dot and after_dot
  1918.                operators.  rms says this is ok.  --karl  */
  1919.             case '=':
  1920.               BUF_PUSH (at_dot);
  1921.               break;
  1922.  
  1923.             case 's':    
  1924.               laststart = b;
  1925.               PATFETCH (c);
  1926.               BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
  1927.               break;
  1928.  
  1929.             case 'S':
  1930.               laststart = b;
  1931.               PATFETCH (c);
  1932.               BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
  1933.               break;
  1934. #endif /* emacs */
  1935.  
  1936.  
  1937.             case 'w':
  1938.               laststart = b;
  1939.               BUF_PUSH (wordchar);
  1940.               break;
  1941.  
  1942.  
  1943.             case 'W':
  1944.               laststart = b;
  1945.               BUF_PUSH (notwordchar);
  1946.               break;
  1947.  
  1948.  
  1949.             case '<':
  1950.               BUF_PUSH (wordbeg);
  1951.               break;
  1952.  
  1953.             case '>':
  1954.               BUF_PUSH (wordend);
  1955.               break;
  1956.  
  1957.             case 'b':
  1958.               BUF_PUSH (wordbound);
  1959.               break;
  1960.  
  1961.             case 'B':
  1962.               BUF_PUSH (notwordbound);
  1963.               break;
  1964.  
  1965.             case '`':
  1966.               BUF_PUSH (begbuf);
  1967.               break;
  1968.  
  1969.             case '\'':
  1970.               BUF_PUSH (endbuf);
  1971.               break;
  1972.  
  1973.             case '1': case '2': case '3': case '4': case '5':
  1974.             case '6': case '7': case '8': case '9':
  1975.               if (syntax & RE_NO_BK_REFS)
  1976.                 goto normal_char;
  1977.  
  1978.               c1 = c - '0';
  1979.  
  1980.               if (c1 > regnum)
  1981.                 return REG_ESUBREG;
  1982.  
  1983.               /* Can't back reference to a subexpression if inside of it.  */
  1984.               if (group_in_compile_stack (compile_stack, c1))
  1985.                 goto normal_char;
  1986.  
  1987.               laststart = b;
  1988.               BUF_PUSH_2 (duplicate, c1);
  1989.               break;
  1990.  
  1991.  
  1992.             case '+':
  1993.             case '?':
  1994.               if (syntax & RE_BK_PLUS_QM)
  1995.                 goto handle_plus;
  1996.               else
  1997.                 goto normal_backslash;
  1998.  
  1999.             default:
  2000.             normal_backslash:
  2001.               /* You might think it would be useful for \ to mean
  2002.                  not to translate; but if we don't translate it
  2003.                  it will never match anything.  */
  2004.               c = TRANSLATE (c);
  2005.               goto normal_char;
  2006.             }
  2007.           break;
  2008.  
  2009.  
  2010.     default:
  2011.         /* Expects the character in `c'.  */
  2012.     normal_char:
  2013.           /* If no exactn currently being built.  */
  2014.           if (!pending_exact 
  2015.  
  2016.               /* If last exactn not at current position.  */
  2017.               || pending_exact + *pending_exact + 1 != b
  2018.               
  2019.               /* We have only one byte following the exactn for the count.  */
  2020.           || *pending_exact == (1 << BYTEWIDTH) - 1
  2021.  
  2022.               /* If followed by a repetition operator.  */
  2023.               || *p == '*' || *p == '^'
  2024.           || ((syntax & RE_BK_PLUS_QM)
  2025.           ? *p == '\\' && (p[1] == '+' || p[1] == '?')
  2026.           : (*p == '+' || *p == '?'))
  2027.           || ((syntax & RE_INTERVALS)
  2028.                   && ((syntax & RE_NO_BK_BRACES)
  2029.               ? *p == '{'
  2030.                       : (p[0] == '\\' && p[1] == '{'))))
  2031.         {
  2032.           /* Start building a new exactn.  */
  2033.               
  2034.               laststart = b;
  2035.  
  2036.           BUF_PUSH_2 (exactn, 0);
  2037.           pending_exact = b - 1;
  2038.             }
  2039.             
  2040.       BUF_PUSH (c);
  2041.           (*pending_exact)++;
  2042.       break;
  2043.         } /* switch (c) */
  2044.     } /* while p != pend */
  2045.  
  2046.   
  2047.   /* Through the pattern now.  */
  2048.   
  2049.   if (fixup_alt_jump)
  2050.     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
  2051.  
  2052.   if (!COMPILE_STACK_EMPTY) 
  2053.     return REG_EPAREN;
  2054.  
  2055.   free (compile_stack.stack);
  2056.  
  2057.   /* We have succeeded; set the length of the buffer.  */
  2058.   bufp->used = b - bufp->buffer;
  2059.  
  2060. #ifdef DEBUG
  2061.   if (debug)
  2062.     {
  2063.       DEBUG_PRINT1 ("\nCompiled pattern: \n");
  2064.       print_compiled_pattern (bufp);
  2065.     }
  2066. #endif /* DEBUG */
  2067.  
  2068.   return REG_NOERROR;
  2069. } /* regex_compile */
  2070.  
  2071. /* Subroutines for `regex_compile'.  */
  2072.  
  2073. /* Store OP at LOC followed by two-byte integer parameter ARG.  */
  2074.  
  2075. static void
  2076. store_op1 (
  2077.     re_opcode_t op,
  2078.     unsigned char *loc,
  2079.     int arg)
  2080. {
  2081.   *loc = (unsigned char) op;
  2082.   STORE_NUMBER (loc + 1, arg);
  2083. }
  2084.  
  2085.  
  2086. /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
  2087.  
  2088. static void
  2089. store_op2 (
  2090.     re_opcode_t op,
  2091.     unsigned char *loc,
  2092.     int arg1, int arg2)
  2093. {
  2094.   *loc = (unsigned char) op;
  2095.   STORE_NUMBER (loc + 1, arg1);
  2096.   STORE_NUMBER (loc + 3, arg2);
  2097. }
  2098.  
  2099.  
  2100. /* Copy the bytes from LOC to END to open up three bytes of space at LOC
  2101.    for OP followed by two-byte integer parameter ARG.  */
  2102.  
  2103. static void
  2104. insert_op1 (
  2105.     re_opcode_t op,
  2106.     unsigned char *loc,
  2107.     int arg,
  2108.     unsigned char *end)
  2109. {
  2110.   register unsigned char *pfrom = end;
  2111.   register unsigned char *pto = end + 3;
  2112.  
  2113.   while (pfrom != loc)
  2114.     *--pto = *--pfrom;
  2115.     
  2116.   store_op1 (op, loc, arg);
  2117. }
  2118.  
  2119.  
  2120. /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
  2121.  
  2122. static void
  2123. insert_op2 (
  2124.     re_opcode_t op,
  2125.     unsigned char *loc,
  2126.     int arg1, int arg2,
  2127.     unsigned char *end)
  2128. {
  2129.   register unsigned char *pfrom = end;
  2130.   register unsigned char *pto = end + 5;
  2131.  
  2132.   while (pfrom != loc)
  2133.     *--pto = *--pfrom;
  2134.     
  2135.   store_op2 (op, loc, arg1, arg2);
  2136. }
  2137.  
  2138.  
  2139. /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
  2140.    after an alternative or a begin-subexpression.  We assume there is at
  2141.    least one character before the ^.  */
  2142.  
  2143. static boolean
  2144. at_begline_loc_p (
  2145.     const char *pattern, const char *p,
  2146.     reg_syntax_t syntax)
  2147. {
  2148.   const char *prev = p - 2;
  2149.   boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
  2150.   
  2151.   return
  2152.        /* After a subexpression?  */
  2153.        (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
  2154.        /* After an alternative?  */
  2155.     || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
  2156. }
  2157.  
  2158.  
  2159. /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
  2160.    at least one character after the $, i.e., `P < PEND'.  */
  2161.  
  2162. static boolean
  2163. at_endline_loc_p (
  2164.     const char *p, const char *pend,
  2165.     int syntax)
  2166. {
  2167.   const char *next = p;
  2168.   boolean next_backslash = *next == '\\';
  2169.   const char *next_next = p + 1 < pend ? p + 1 : NULL;
  2170.   
  2171.   return
  2172.        /* Before a subexpression?  */
  2173.        (syntax & RE_NO_BK_PARENS ? *next == ')'
  2174.         : next_backslash && next_next && *next_next == ')')
  2175.        /* Before an alternative?  */
  2176.     || (syntax & RE_NO_BK_VBAR ? *next == '|'
  2177.         : next_backslash && next_next && *next_next == '|');
  2178. }
  2179.  
  2180.  
  2181. /* Returns true if REGNUM is in one of COMPILE_STACK's elements and 
  2182.    false if it's not.  */
  2183.  
  2184. static boolean
  2185. group_in_compile_stack (
  2186.     compile_stack_type compile_stack,
  2187.     regnum_t regnum)
  2188. {
  2189.   int this_element;
  2190.  
  2191.   for (this_element = compile_stack.avail - 1;  
  2192.        this_element >= 0; 
  2193.        this_element--)
  2194.     if (compile_stack.stack[this_element].regnum == regnum)
  2195.       return true;
  2196.  
  2197.   return false;
  2198. }
  2199.  
  2200.  
  2201. /* Read the ending character of a range (in a bracket expression) from the
  2202.    uncompiled pattern *P_PTR (which ends at PEND).  We assume the
  2203.    starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
  2204.    Then we set the translation of all bits between the starting and
  2205.    ending characters (inclusive) in the compiled pattern B.
  2206.    
  2207.    Return an error code.
  2208.    
  2209.    We use these short variable names so we can use the same macros as
  2210.    `regex_compile' itself.  */
  2211.  
  2212. static reg_errcode_t
  2213. compile_range (
  2214.     const char **p_ptr, const char *pend,
  2215.     char *translate,
  2216.     reg_syntax_t syntax,
  2217.     unsigned char *b)
  2218. {
  2219.   unsigned this_char;
  2220.  
  2221.   const char *p = *p_ptr;
  2222.   int range_start, range_end;
  2223.   
  2224.   if (p == pend)
  2225.     return REG_ERANGE;
  2226.  
  2227.   /* Even though the pattern is a signed `char *', we need to fetch
  2228.      with unsigned char *'s; if the high bit of the pattern character
  2229.      is set, the range endpoints will be negative if we fetch using a
  2230.      signed char *.
  2231.  
  2232.      We also want to fetch the endpoints without translating them; the 
  2233.      appropriate translation is done in the bit-setting loop below.  */
  2234.   range_start = ((unsigned char *) p)[-2];
  2235.   range_end   = ((unsigned char *) p)[0];
  2236.  
  2237.   /* Have to increment the pointer into the pattern string, so the
  2238.      caller isn't still at the ending character.  */
  2239.   (*p_ptr)++;
  2240.  
  2241.   /* If the start is after the end, the range is empty.  */
  2242.   if (range_start > range_end)
  2243.     return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
  2244.  
  2245.   /* Here we see why `this_char' has to be larger than an `unsigned
  2246.      char' -- the range is inclusive, so if `range_end' == 0xff
  2247.      (assuming 8-bit characters), we would otherwise go into an infinite
  2248.      loop, since all characters <= 0xff.  */
  2249.   for (this_char = range_start; this_char <= range_end; this_char++)
  2250.     {
  2251.       SET_LIST_BIT (TRANSLATE (this_char));
  2252.     }
  2253.   
  2254.   return REG_NOERROR;
  2255. }
  2256.  
  2257. /* Failure stack declarations and macros; both re_compile_fastmap and
  2258.    re_match_2 use a failure stack.  These have to be macros because of
  2259.    REGEX_ALLOCATE.  */
  2260.    
  2261.  
  2262. /* Number of failure points for which to initially allocate space
  2263.    when matching.  If this number is exceeded, we allocate more
  2264.    space, so it is not a hard limit.  */
  2265. #ifndef INIT_FAILURE_ALLOC
  2266. #define INIT_FAILURE_ALLOC 5
  2267. #endif
  2268.  
  2269. /* Roughly the maximum number of failure points on the stack.  Would be
  2270.    exactly that if always used MAX_FAILURE_SPACE each time we failed.
  2271.    This is a variable only so users of regex can assign to it; we never
  2272.    change it ourselves.  */
  2273. int re_max_failures = 2000;
  2274.  
  2275. typedef const unsigned char *fail_stack_elt_t;
  2276.  
  2277. typedef struct
  2278. {
  2279.   fail_stack_elt_t *stack;
  2280.   unsigned size;
  2281.   unsigned avail;            /* Offset of next open position.  */
  2282. } fail_stack_type;
  2283.  
  2284. #define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
  2285. #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
  2286. #define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
  2287. #define FAIL_STACK_TOP()       (fail_stack.stack[fail_stack.avail])
  2288.  
  2289.  
  2290. /* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
  2291.  
  2292. #define INIT_FAIL_STACK()                        \
  2293.   do {                                    \
  2294.     fail_stack.stack = (fail_stack_elt_t *)                \
  2295.       REGEX_ALLOCATE (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));    \
  2296.                                     \
  2297.     if (fail_stack.stack == NULL)                    \
  2298.       return -2;                            \
  2299.                                     \
  2300.     fail_stack.size = INIT_FAILURE_ALLOC;                \
  2301.     fail_stack.avail = 0;                        \
  2302.   } while (0)
  2303.  
  2304.  
  2305. /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
  2306.  
  2307.    Return 1 if succeeds, and 0 if either ran out of memory
  2308.    allocating space for it or it was already too large.  
  2309.    
  2310.    REGEX_REALLOCATE requires `destination' be declared.   */
  2311.  
  2312. #define DOUBLE_FAIL_STACK(fail_stack)                    \
  2313.   ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS        \
  2314.    ? 0                                    \
  2315.    : ((fail_stack).stack = (fail_stack_elt_t *)                \
  2316.         REGEX_REALLOCATE ((fail_stack).stack,                 \
  2317.           (fail_stack).size * sizeof (fail_stack_elt_t),        \
  2318.           ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),    \
  2319.                                     \
  2320.       (fail_stack).stack == NULL                    \
  2321.       ? 0                                \
  2322.       : ((fail_stack).size <<= 1,                     \
  2323.          1)))
  2324.  
  2325.  
  2326. /* Push PATTERN_OP on FAIL_STACK. 
  2327.  
  2328.    Return 1 if was able to do so and 0 if ran out of memory allocating
  2329.    space to do so.  */
  2330. #define PUSH_PATTERN_OP(pattern_op, fail_stack)                \
  2331.   ((FAIL_STACK_FULL ()                            \
  2332.     && !DOUBLE_FAIL_STACK (fail_stack))                    \
  2333.     ? 0                                    \
  2334.     : ((fail_stack).stack[(fail_stack).avail++] = pattern_op,        \
  2335.        1))
  2336.  
  2337. /* This pushes an item onto the failure stack.  Must be a four-byte
  2338.    value.  Assumes the variable `fail_stack'.  Probably should only
  2339.    be called from within `PUSH_FAILURE_POINT'.  */
  2340. #define PUSH_FAILURE_ITEM(item)                        \
  2341.   fail_stack.stack[fail_stack.avail++] = (fail_stack_elt_t) item
  2342.  
  2343. /* The complement operation.  Assumes `fail_stack' is nonempty.  */
  2344. #define POP_FAILURE_ITEM() fail_stack.stack[--fail_stack.avail]
  2345.  
  2346. /* Used to omit pushing failure point id's when we're not debugging.  */
  2347. #ifdef DEBUG
  2348. #define DEBUG_PUSH PUSH_FAILURE_ITEM
  2349. #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_ITEM ()
  2350. #else
  2351. #define DEBUG_PUSH(item)
  2352. #define DEBUG_POP(item_addr)
  2353. #endif
  2354.  
  2355.  
  2356. /* Push the information about the state we will need
  2357.    if we ever fail back to it.  
  2358.    
  2359.    Requires variables fail_stack, regstart, regend, reg_info, and
  2360.    num_regs be declared.  DOUBLE_FAIL_STACK requires `destination' be
  2361.    declared.
  2362.    
  2363.    Does `return FAILURE_CODE' if runs out of memory.  */
  2364.  
  2365. #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)    \
  2366.   do {                                    \
  2367.     char *destination;                            \
  2368.     /* Must be int, so when we don't save any registers, the arithmetic    \
  2369.        of 0 + -1 isn't done as unsigned.  */                \
  2370.     int this_reg;                            \
  2371.                                         \
  2372.     DEBUG_STATEMENT (failure_id++);                    \
  2373.     DEBUG_STATEMENT (nfailure_points_pushed++);                \
  2374.     DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);        \
  2375.     DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
  2376.     DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
  2377.                                     \
  2378.     DEBUG_PRINT2 ("  slots needed: %d\n", NUM_FAILURE_ITEMS);        \
  2379.     DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);    \
  2380.                                     \
  2381.     /* Ensure we have enough space allocated for what we will push.  */    \
  2382.     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)            \
  2383.       {                                    \
  2384.         if (!DOUBLE_FAIL_STACK (fail_stack))            \
  2385.           return failure_code;                        \
  2386.                                     \
  2387.         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",        \
  2388.                (fail_stack).size);                \
  2389.         DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
  2390.       }                                    \
  2391.                                     \
  2392.     /* Push the info, starting with the registers.  */            \
  2393.     DEBUG_PRINT1 ("\n");                        \
  2394.                                     \
  2395.     for (this_reg = lowest_active_reg; this_reg <= highest_active_reg;    \
  2396.          this_reg++)                            \
  2397.       {                                    \
  2398.     DEBUG_PRINT2 ("  Pushing reg: %d\n", this_reg);            \
  2399.         DEBUG_STATEMENT (num_regs_pushed++);                \
  2400.                                     \
  2401.     DEBUG_PRINT2 ("    start: 0x%x\n", regstart[this_reg]);        \
  2402.         PUSH_FAILURE_ITEM (regstart[this_reg]);                \
  2403.                                                                         \
  2404.     DEBUG_PRINT2 ("    end: 0x%x\n", regend[this_reg]);        \
  2405.         PUSH_FAILURE_ITEM (regend[this_reg]);                \
  2406.                                     \
  2407.     DEBUG_PRINT2 ("    info: 0x%x\n      ", reg_info[this_reg]);    \
  2408.         DEBUG_PRINT2 (" match_null=%d",                    \
  2409.                       REG_MATCH_NULL_STRING_P (reg_info[this_reg]));    \
  2410.         DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));    \
  2411.         DEBUG_PRINT2 (" matched_something=%d",                \
  2412.                       MATCHED_SOMETHING (reg_info[this_reg]));        \
  2413.         DEBUG_PRINT2 (" ever_matched=%d",                \
  2414.                       EVER_MATCHED_SOMETHING (reg_info[this_reg]));    \
  2415.     DEBUG_PRINT1 ("\n");                        \
  2416.         PUSH_FAILURE_ITEM (reg_info[this_reg].word);            \
  2417.       }                                    \
  2418.                                     \
  2419.     DEBUG_PRINT2 ("  Pushing  low active reg: %d\n", lowest_active_reg);\
  2420.     PUSH_FAILURE_ITEM (lowest_active_reg);                \
  2421.                                     \
  2422.     DEBUG_PRINT2 ("  Pushing high active reg: %d\n", highest_active_reg);\
  2423.     PUSH_FAILURE_ITEM (highest_active_reg);                \
  2424.                                     \
  2425.     DEBUG_PRINT2 ("  Pushing pattern 0x%x: ", pattern_place);        \
  2426.     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);        \
  2427.     PUSH_FAILURE_ITEM (pattern_place);                    \
  2428.                                     \
  2429.     DEBUG_PRINT2 ("  Pushing string 0x%x: `", string_place);        \
  2430.     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
  2431.                  size2);                \
  2432.     DEBUG_PRINT1 ("'\n");                        \
  2433.     PUSH_FAILURE_ITEM (string_place);                    \
  2434.                                     \
  2435.     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);        \
  2436.     DEBUG_PUSH (failure_id);                        \
  2437.   } while (0)
  2438.  
  2439. /* This is the number of items that are pushed and popped on the stack
  2440.    for each register.  */
  2441. #define NUM_REG_ITEMS  3
  2442.  
  2443. /* Individual items aside from the registers.  */
  2444. #ifdef DEBUG
  2445. #define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
  2446. #else
  2447. #define NUM_NONREG_ITEMS 4
  2448. #endif
  2449.  
  2450. /* We push at most this many items on the stack.  */
  2451. #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
  2452.  
  2453. /* We actually push this many items.  */
  2454. #define NUM_FAILURE_ITEMS                        \
  2455.   ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS     \
  2456.     + NUM_NONREG_ITEMS)
  2457.  
  2458. /* How many items can still be added to the stack without overflowing it.  */
  2459. #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
  2460.  
  2461.  
  2462. /* Pops what PUSH_FAIL_STACK pushes.
  2463.  
  2464.    We restore into the parameters, all of which should be lvalues:
  2465.      STR -- the saved data position.
  2466.      PAT -- the saved pattern position.
  2467.      LOW_REG, HIGH_REG -- the highest and lowest active registers.
  2468.      REGSTART, REGEND -- arrays of string positions.
  2469.      REG_INFO -- array of information about each subexpression.
  2470.    
  2471.    Also assumes the variables `fail_stack' and (if debugging), `bufp',
  2472.    `pend', `string1', `size1', `string2', and `size2'.  */
  2473.  
  2474. #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
  2475. {                                    \
  2476.   DEBUG_STATEMENT (fail_stack_elt_t failure_id;)            \
  2477.   int this_reg;                                \
  2478.   const unsigned char *string_temp;                    \
  2479.                                     \
  2480.   assert (!FAIL_STACK_EMPTY ());                    \
  2481.                                     \
  2482.   /* Remove failure points and point to how many regs pushed.  */    \
  2483.   DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");                \
  2484.   DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);    \
  2485.   DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);    \
  2486.                                     \
  2487.   assert (fail_stack.avail >= NUM_NONREG_ITEMS);            \
  2488.                                     \
  2489.   DEBUG_POP (&failure_id);                        \
  2490.   DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);        \
  2491.                                     \
  2492.   /* If the saved string location is NULL, it came from an        \
  2493.      on_failure_keep_string_jump opcode, and we want to throw away the    \
  2494.      saved NULL, thus retaining our current position in the string.  */    \
  2495.   string_temp = POP_FAILURE_ITEM ();                    \
  2496.   if (string_temp != NULL)                        \
  2497.     str = (const char *) string_temp;                    \
  2498.                                     \
  2499.   DEBUG_PRINT2 ("  Popping string 0x%x: `", str);            \
  2500.   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);    \
  2501.   DEBUG_PRINT1 ("'\n");                            \
  2502.                                     \
  2503.   pat = (unsigned char *) POP_FAILURE_ITEM ();                \
  2504.   DEBUG_PRINT2 ("  Popping pattern 0x%x: ", pat);            \
  2505.   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);            \
  2506.                                     \
  2507.   /* Restore register info.  */                        \
  2508.   high_reg = (unsigned) POP_FAILURE_ITEM ();                \
  2509.   DEBUG_PRINT2 ("  Popping high active reg: %d\n", high_reg);        \
  2510.                                     \
  2511.   low_reg = (unsigned) POP_FAILURE_ITEM ();                \
  2512.   DEBUG_PRINT2 ("  Popping  low active reg: %d\n", low_reg);        \
  2513.                                     \
  2514.   for (this_reg = high_reg; this_reg >= low_reg; this_reg--)        \
  2515.     {                                    \
  2516.       DEBUG_PRINT2 ("    Popping reg: %d\n", this_reg);            \
  2517.                                     \
  2518.       reg_info[this_reg].word = POP_FAILURE_ITEM ();            \
  2519.       DEBUG_PRINT2 ("      info: 0x%x\n", reg_info[this_reg]);        \
  2520.                                     \
  2521.       regend[this_reg] = (const char *) POP_FAILURE_ITEM ();        \
  2522.       DEBUG_PRINT2 ("      end: 0x%x\n", regend[this_reg]);        \
  2523.                                     \
  2524.       regstart[this_reg] = (const char *) POP_FAILURE_ITEM ();        \
  2525.       DEBUG_PRINT2 ("      start: 0x%x\n", regstart[this_reg]);        \
  2526.     }                                    \
  2527.                                     \
  2528.   DEBUG_STATEMENT (nfailure_points_popped++);                \
  2529. } /* POP_FAILURE_POINT */
  2530.  
  2531. /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
  2532.    BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
  2533.    characters can start a string that matches the pattern.  This fastmap
  2534.    is used by re_search to skip quickly over impossible starting points.
  2535.  
  2536.    The caller must supply the address of a (1 << BYTEWIDTH)-byte data
  2537.    area as BUFP->fastmap.
  2538.    
  2539.    We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
  2540.    the pattern buffer.
  2541.  
  2542.    Returns 0 if we succeed, -2 if an internal error.   */
  2543.  
  2544. int
  2545. re_compile_fastmap (bufp)
  2546.      struct re_pattern_buffer *bufp;
  2547. {
  2548.   int j, k;
  2549.   fail_stack_type fail_stack;
  2550. #ifndef REGEX_MALLOC
  2551.   char *destination;
  2552. #endif
  2553.   /* We don't push any register information onto the failure stack.  */
  2554.   unsigned num_regs = 0;
  2555.   
  2556.   register char *fastmap = bufp->fastmap;
  2557.   unsigned char *pattern = bufp->buffer;
  2558.   unsigned long size = bufp->used;
  2559.   const unsigned char *p = pattern;
  2560.   register unsigned char *pend = pattern + size;
  2561.  
  2562.   /* Assume that each path through the pattern can be null until
  2563.      proven otherwise.  We set this false at the bottom of switch
  2564.      statement, to which we get only if a particular path doesn't
  2565.      match the empty string.  */
  2566.   boolean path_can_be_null = true;
  2567.  
  2568.   /* We aren't doing a `succeed_n' to begin with.  */
  2569.   boolean succeed_n_p = false;
  2570.  
  2571.   assert (fastmap != NULL && p != NULL);
  2572.   
  2573.   INIT_FAIL_STACK ();
  2574.   bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
  2575.   bufp->fastmap_accurate = 1;        /* It will be when we're done.  */
  2576.   bufp->can_be_null = 0;
  2577.       
  2578.   while (p != pend || !FAIL_STACK_EMPTY ())
  2579.     {
  2580.       if (p == pend)
  2581.         {
  2582.           bufp->can_be_null |= path_can_be_null;
  2583.           
  2584.           /* Reset for next path.  */
  2585.           path_can_be_null = true;
  2586.           
  2587.           p = fail_stack.stack[--fail_stack.avail];
  2588.     }
  2589.  
  2590.       /* We should never be about to go beyond the end of the pattern.  */
  2591.       assert (p < pend);
  2592.       
  2593. #ifdef SWITCH_ENUM_BUG
  2594.       switch ((int) ((re_opcode_t) *p++))
  2595. #else
  2596.       switch ((re_opcode_t) *p++)
  2597. #endif
  2598.     {
  2599.  
  2600.         /* I guess the idea here is to simply not bother with a fastmap
  2601.            if a backreference is used, since it's too hard to figure out
  2602.            the fastmap for the corresponding group.  Setting
  2603.            `can_be_null' stops `re_search_2' from using the fastmap, so
  2604.            that is all we do.  */
  2605.     case duplicate:
  2606.       bufp->can_be_null = 1;
  2607.           return 0;
  2608.  
  2609.  
  2610.       /* Following are the cases which match a character.  These end
  2611.          with `break'.  */
  2612.  
  2613.     case exactn:
  2614.           fastmap[p[1]] = 1;
  2615.       break;
  2616.  
  2617.  
  2618.         case charset:
  2619.           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  2620.         if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
  2621.               fastmap[j] = 1;
  2622.       break;
  2623.  
  2624.  
  2625.     case charset_not:
  2626.       /* Chars beyond end of map must be allowed.  */
  2627.       for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
  2628.             fastmap[j] = 1;
  2629.  
  2630.       for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
  2631.         if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
  2632.               fastmap[j] = 1;
  2633.           break;
  2634.  
  2635.  
  2636.     case wordchar:
  2637.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2638.         if (SYNTAX (j) == Sword)
  2639.           fastmap[j] = 1;
  2640.       break;
  2641.  
  2642.  
  2643.     case notwordchar:
  2644.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2645.         if (SYNTAX (j) != Sword)
  2646.           fastmap[j] = 1;
  2647.       break;
  2648.  
  2649.  
  2650.         case anychar:
  2651.           /* `.' matches anything ...  */
  2652.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2653.             fastmap[j] = 1;
  2654.  
  2655.           /* ... except perhaps newline.  */
  2656.           if (!(bufp->syntax & RE_DOT_NEWLINE))
  2657.             fastmap['\n'] = 0;
  2658.  
  2659.           /* Return if we have already set `can_be_null'; if we have,
  2660.              then the fastmap is irrelevant.  Something's wrong here.  */
  2661.       else if (bufp->can_be_null)
  2662.         return 0;
  2663.  
  2664.           /* Otherwise, have to check alternative paths.  */
  2665.       break;
  2666.  
  2667.  
  2668. #ifdef emacs
  2669.         case syntaxspec:
  2670.       k = *p++;
  2671.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2672.         if (SYNTAX (j) == (enum syntaxcode) k)
  2673.           fastmap[j] = 1;
  2674.       break;
  2675.  
  2676.  
  2677.     case notsyntaxspec:
  2678.       k = *p++;
  2679.       for (j = 0; j < (1 << BYTEWIDTH); j++)
  2680.         if (SYNTAX (j) != (enum syntaxcode) k)
  2681.           fastmap[j] = 1;
  2682.       break;
  2683.  
  2684.  
  2685.       /* All cases after this match the empty string.  These end with
  2686.          `continue'.  */
  2687.  
  2688.  
  2689.     case before_dot:
  2690.     case at_dot:
  2691.     case after_dot:
  2692.           continue;
  2693. #endif /* not emacs */
  2694.  
  2695.  
  2696.         case no_op:
  2697.         case begline:
  2698.         case endline:
  2699.     case begbuf:
  2700.     case endbuf:
  2701.     case wordbound:
  2702.     case notwordbound:
  2703.     case wordbeg:
  2704.     case wordend:
  2705.         case push_dummy_failure:
  2706.           continue;
  2707.  
  2708.  
  2709.     case jump_n:
  2710.         case pop_failure_jump:
  2711.     case maybe_pop_jump:
  2712.     case jump:
  2713.         case jump_past_alt:
  2714.     case dummy_failure_jump:
  2715.           EXTRACT_NUMBER_AND_INCR (j, p);
  2716.       p += j;    
  2717.       if (j > 0)
  2718.         continue;
  2719.             
  2720.           /* Jump backward implies we just went through the body of a
  2721.              loop and matched nothing.  Opcode jumped to should be
  2722.              `on_failure_jump' or `succeed_n'.  Just treat it like an
  2723.              ordinary jump.  For a * loop, it has pushed its failure
  2724.              point already; if so, discard that as redundant.  */
  2725.           if ((re_opcode_t) *p != on_failure_jump
  2726.           && (re_opcode_t) *p != succeed_n)
  2727.         continue;
  2728.  
  2729.           p++;
  2730.           EXTRACT_NUMBER_AND_INCR (j, p);
  2731.           p += j;        
  2732.       
  2733.           /* If what's on the stack is where we are now, pop it.  */
  2734.           if (!FAIL_STACK_EMPTY () 
  2735.           && fail_stack.stack[fail_stack.avail - 1] == p)
  2736.             fail_stack.avail--;
  2737.  
  2738.           continue;
  2739.  
  2740.  
  2741.         case on_failure_jump:
  2742.         case on_failure_keep_string_jump:
  2743.     handle_on_failure_jump:
  2744.           EXTRACT_NUMBER_AND_INCR (j, p);
  2745.  
  2746.           /* For some patterns, e.g., `(a?)?', `p+j' here points to the
  2747.              end of the pattern.  We don't want to push such a point,
  2748.              since when we restore it above, entering the switch will
  2749.              increment `p' past the end of the pattern.  We don't need
  2750.              to push such a point since we obviously won't find any more
  2751.              fastmap entries beyond `pend'.  Such a pattern can match
  2752.              the null string, though.  */
  2753.           if (p + j < pend)
  2754.             {
  2755.               if (!PUSH_PATTERN_OP (p + j, fail_stack))
  2756.                 return -2;
  2757.             }
  2758.           else
  2759.             bufp->can_be_null = 1;
  2760.  
  2761.           if (succeed_n_p)
  2762.             {
  2763.               EXTRACT_NUMBER_AND_INCR (k, p);    /* Skip the n.  */
  2764.               succeed_n_p = false;
  2765.         }
  2766.  
  2767.           continue;
  2768.  
  2769.  
  2770.     case succeed_n:
  2771.           /* Get to the number of times to succeed.  */
  2772.           p += 2;        
  2773.  
  2774.           /* Increment p past the n for when k != 0.  */
  2775.           EXTRACT_NUMBER_AND_INCR (k, p);
  2776.           if (k == 0)
  2777.         {
  2778.               p -= 4;
  2779.             succeed_n_p = true;  /* Spaghetti code alert.  */
  2780.               goto handle_on_failure_jump;
  2781.             }
  2782.           continue;
  2783.  
  2784.  
  2785.     case set_number_at:
  2786.           p += 4;
  2787.           continue;
  2788.  
  2789.  
  2790.     case start_memory:
  2791.         case stop_memory:
  2792.       p += 2;
  2793.       continue;
  2794.  
  2795.  
  2796.     default:
  2797.           abort (); /* We have listed all the cases.  */
  2798.         } /* switch *p++ */
  2799.  
  2800.       /* Getting here means we have found the possible starting
  2801.          characters for one path of the pattern -- and that the empty
  2802.          string does not match.  We need not follow this path further.
  2803.          Instead, look at the next alternative (remembered on the
  2804.          stack), or quit if no more.  The test at the top of the loop
  2805.          does these things.  */
  2806.       path_can_be_null = false;
  2807.       p = pend;
  2808.     } /* while p */
  2809.  
  2810.   /* Set `can_be_null' for the last path (also the first path, if the
  2811.      pattern is empty).  */
  2812.   bufp->can_be_null |= path_can_be_null;
  2813.   return 0;
  2814. } /* re_compile_fastmap */
  2815.  
  2816. /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
  2817.    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
  2818.    this memory for recording register information.  STARTS and ENDS
  2819.    must be allocated using the malloc library routine, and must each
  2820.    be at least NUM_REGS * sizeof (regoff_t) bytes long.
  2821.  
  2822.    If NUM_REGS == 0, then subsequent matches should allocate their own
  2823.    register data.
  2824.  
  2825.    Unless this function is called, the first search or match using
  2826.    PATTERN_BUFFER will allocate its own register data, without
  2827.    freeing the old data.  */
  2828.  
  2829. void
  2830. re_set_registers (bufp, regs, num_regs, starts, ends)
  2831.     struct re_pattern_buffer *bufp;
  2832.     struct re_registers *regs;
  2833.     unsigned num_regs;
  2834.     regoff_t *starts, *ends;
  2835. {
  2836.   if (num_regs)
  2837.     {
  2838.       bufp->regs_allocated = REGS_REALLOCATE;
  2839.       regs->num_regs = num_regs;
  2840.       regs->start = starts;
  2841.       regs->end = ends;
  2842.     }
  2843.   else
  2844.     {
  2845.       bufp->regs_allocated = REGS_UNALLOCATED;
  2846.       regs->num_regs = 0;
  2847.       regs->start = regs->end = (regoff_t) 0;
  2848.     }
  2849. }
  2850.  
  2851. /* Searching routines.  */
  2852.  
  2853. /* Like re_search_2, below, but only one string is specified, and
  2854.    doesn't let you say where to stop matching. */
  2855.  
  2856. int
  2857. re_search (bufp, string, size, startpos, range, regs)
  2858.      struct re_pattern_buffer *bufp;
  2859.      const char *string;
  2860.      int size, startpos, range;
  2861.      struct re_registers *regs;
  2862. {
  2863.   return re_search_2 (bufp, NULL, 0, string, size, startpos, range, 
  2864.               regs, size);
  2865. }
  2866.  
  2867.  
  2868. /* Using the compiled pattern in BUFP->buffer, first tries to match the
  2869.    virtual concatenation of STRING1 and STRING2, starting first at index
  2870.    STARTPOS, then at STARTPOS + 1, and so on.
  2871.    
  2872.    STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
  2873.    
  2874.    RANGE is how far to scan while trying to match.  RANGE = 0 means try
  2875.    only at STARTPOS; in general, the last start tried is STARTPOS +
  2876.    RANGE.
  2877.    
  2878.    In REGS, return the indices of the virtual concatenation of STRING1
  2879.    and STRING2 that matched the entire BUFP->buffer and its contained
  2880.    subexpressions.
  2881.    
  2882.    Do not consider matching one past the index STOP in the virtual
  2883.    concatenation of STRING1 and STRING2.
  2884.  
  2885.    We return either the position in the strings at which the match was
  2886.    found, -1 if no match, or -2 if error (such as failure
  2887.    stack overflow).  */
  2888.  
  2889. int
  2890. re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
  2891.      struct re_pattern_buffer *bufp;
  2892.      const char *string1, *string2;
  2893.      int size1, size2;
  2894.      int startpos;
  2895.      int range;
  2896.      struct re_registers *regs;
  2897.      int stop;
  2898. {
  2899.   int val;
  2900.   register char *fastmap = bufp->fastmap;
  2901.   register char *translate = bufp->translate;
  2902.   int total_size = size1 + size2;
  2903.   int endpos = startpos + range;
  2904.  
  2905.   /* Check for out-of-range STARTPOS.  */
  2906.   if (startpos < 0 || startpos > total_size)
  2907.     return -1;
  2908.     
  2909.   /* Fix up RANGE if it might eventually take us outside
  2910.      the virtual concatenation of STRING1 and STRING2.  */
  2911.   if (endpos < -1)
  2912.     range = -1 - startpos;
  2913.   else if (endpos > total_size)
  2914.     range = total_size - startpos;
  2915.  
  2916.   /* If the search isn't to be a backwards one, don't waste time in a
  2917.      search for a pattern that must be anchored.  */
  2918.   if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
  2919.     {
  2920.       if (startpos > 0)
  2921.     return -1;
  2922.       else
  2923.     range = 1;
  2924.     }
  2925.  
  2926.   /* Update the fastmap now if not correct already.  */
  2927.   if (fastmap && !bufp->fastmap_accurate)
  2928.     if (re_compile_fastmap (bufp) == -2)
  2929.       return -2;
  2930.   
  2931.   /* Loop through the string, looking for a place to start matching.  */
  2932.   for (;;)
  2933.     { 
  2934.       /* If a fastmap is supplied, skip quickly over characters that
  2935.          cannot be the start of a match.  If the pattern can match the
  2936.          null string, however, we don't need to skip characters; we want
  2937.          the first null string.  */
  2938.       if (fastmap && startpos < total_size && !bufp->can_be_null)
  2939.     {
  2940.       if (range > 0)    /* Searching forwards.  */
  2941.         {
  2942.           register const char *d;
  2943.           register int lim = 0;
  2944.           int irange = range;
  2945.  
  2946.               if (startpos < size1 && startpos + range >= size1)
  2947.                 lim = range - (size1 - startpos);
  2948.  
  2949.           d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
  2950.    
  2951.               /* Written out as an if-else to avoid testing `translate'
  2952.                  inside the loop.  */
  2953.           if (translate)
  2954.                 while (range > lim
  2955.                        && !fastmap[(unsigned char)
  2956.                    translate[(unsigned char) *d++]])
  2957.                   range--;
  2958.           else
  2959.                 while (range > lim && !fastmap[(unsigned char) *d++])
  2960.                   range--;
  2961.  
  2962.           startpos += irange - range;
  2963.         }
  2964.       else                /* Searching backwards.  */
  2965.         {
  2966.           register char c = (size1 == 0 || startpos >= size1
  2967.                                  ? string2[startpos - size1] 
  2968.                                  : string1[startpos]);
  2969.  
  2970.           if (!fastmap[(unsigned char) TRANSLATE (c)])
  2971.         goto advance;
  2972.         }
  2973.     }
  2974.  
  2975.       /* If can't match the null string, and that's all we have left, fail.  */
  2976.       if (range >= 0 && startpos == total_size && fastmap
  2977.           && !bufp->can_be_null)
  2978.     return -1;
  2979.  
  2980.       val = re_match_2 (bufp, string1, size1, string2, size2,
  2981.                     startpos, regs, stop);
  2982.       if (val >= 0)
  2983.     return startpos;
  2984.         
  2985.       if (val == -2)
  2986.     return -2;
  2987.  
  2988.     advance:
  2989.       if (!range) 
  2990.         break;
  2991.       else if (range > 0) 
  2992.         {
  2993.           range--; 
  2994.           startpos++;
  2995.         }
  2996.       else
  2997.         {
  2998.           range++; 
  2999.           startpos--;
  3000.         }
  3001.     }
  3002.   return -1;
  3003. } /* re_search_2 */
  3004.  
  3005. /* Declarations and macros for re_match_2.  */
  3006.  
  3007. static int bcmp_translate (
  3008.      unsigned char *s1, unsigned char *s2,
  3009.      register int len,
  3010.      char *translate);
  3011.  
  3012. /* Structure for per-register (a.k.a. per-group) information.
  3013.    This must not be longer than one word, because we push this value
  3014.    onto the failure stack.  Other register information, such as the
  3015.    starting and ending positions (which are addresses), and the list of
  3016.    inner groups (which is a bits list) are maintained in separate
  3017.    variables.  
  3018.    
  3019.    We are making a (strictly speaking) nonportable assumption here: that
  3020.    the compiler will pack our bit fields into something that fits into
  3021.    the type of `word', i.e., is something that fits into one item on the
  3022.    failure stack.  */
  3023. typedef union
  3024. {
  3025.   fail_stack_elt_t word;
  3026.   struct
  3027.   {
  3028.       /* This field is one if this group can match the empty string,
  3029.          zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
  3030. #define MATCH_NULL_UNSET_VALUE 3
  3031.     unsigned match_null_string_p : 2;
  3032.     unsigned is_active : 1;
  3033.     unsigned matched_something : 1;
  3034.     unsigned ever_matched_something : 1;
  3035.   } bits;
  3036. } register_info_type;
  3037.  
  3038. static boolean
  3039. alt_match_null_string_p (
  3040.     unsigned char *p, unsigned char *end,
  3041.     register_info_type *reg_info);
  3042. static boolean
  3043. common_op_match_null_string_p (
  3044.     unsigned char **p, unsigned char *end,
  3045.     register_info_type *reg_info);
  3046.  
  3047. static    boolean group_match_null_string_p (
  3048.             unsigned char **p, unsigned char *end,
  3049.             register_info_type *reg_info);
  3050. #define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
  3051. #define IS_ACTIVE(R)  ((R).bits.is_active)
  3052. #define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
  3053. #define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
  3054.  
  3055.  
  3056. /* Call this when have matched a real character; it sets `matched' flags
  3057.    for the subexpressions which we are currently inside.  Also records
  3058.    that those subexprs have matched.  */
  3059. #define SET_REGS_MATCHED()                        \
  3060.   do                                    \
  3061.     {                                    \
  3062.       unsigned r;                            \
  3063.       for (r = lowest_active_reg; r <= highest_active_reg; r++)        \
  3064.         {                                \
  3065.           MATCHED_SOMETHING (reg_info[r])                \
  3066.             = EVER_MATCHED_SOMETHING (reg_info[r])            \
  3067.             = 1;                            \
  3068.         }                                \
  3069.     }                                    \
  3070.   while (0)
  3071.  
  3072.  
  3073. /* This converts PTR, a pointer into one of the search strings `string1'
  3074.    and `string2' into an offset from the beginning of that string.  */
  3075. #define POINTER_TO_OFFSET(ptr)                        \
  3076.   (FIRST_STRING_P (ptr) ? (ptr) - string1 : (ptr) - string2 + size1)
  3077.  
  3078. /* Registers are set to a sentinel when they haven't yet matched.  */
  3079. #define REG_UNSET_VALUE ((char *) -1)
  3080. #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
  3081.  
  3082.  
  3083. /* Macros for dealing with the split strings in re_match_2.  */
  3084.  
  3085. #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
  3086.  
  3087. /* Call before fetching a character with *d.  This switches over to
  3088.    string2 if necessary.  */
  3089. #define PREFETCH()                            \
  3090.   while (d == dend)                                \
  3091.     {                                    \
  3092.       /* End of string2 => fail.  */                    \
  3093.       if (dend == end_match_2)                         \
  3094.         goto fail;                            \
  3095.       /* End of string1 => advance to string2.  */             \
  3096.       d = string2;                                \
  3097.       dend = end_match_2;                        \
  3098.     }
  3099.  
  3100.  
  3101. /* Test if at very beginning or at very end of the virtual concatenation
  3102.    of `string1' and `string2'.  If only one string, it's `string2'.  */
  3103. #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
  3104. #define AT_STRINGS_END(d) ((d) == end2)    
  3105.  
  3106.  
  3107. /* Test if D points to a character which is word-constituent.  We have
  3108.    two special cases to check for: if past the end of string1, look at
  3109.    the first character in string2; and if before the beginning of
  3110.    string2, look at the last character in string1.  */
  3111. #define WORDCHAR_P(d)                            \
  3112.   (SYNTAX ((d) == end1 ? *string2                    \
  3113.            : (d) == string2 - 1 ? *(end1 - 1) : *(d))            \
  3114.    == Sword)
  3115.  
  3116. /* Test if the character before D and the one at D differ with respect
  3117.    to being word-constituent.  */
  3118. #define AT_WORD_BOUNDARY(d)                        \
  3119.   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                \
  3120.    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
  3121.  
  3122.  
  3123. /* Free everything we malloc.  */
  3124. #ifdef REGEX_MALLOC
  3125. #define FREE_VAR(var) if (var) free (var); var = NULL
  3126. #define FREE_VARIABLES()                        \
  3127.   do {                                    \
  3128.     FREE_VAR (fail_stack.stack);                    \
  3129.     FREE_VAR (regstart);                        \
  3130.     FREE_VAR (regend);                            \
  3131.     FREE_VAR (old_regstart);                        \
  3132.     FREE_VAR (old_regend);                        \
  3133.     FREE_VAR (best_regstart);                        \
  3134.     FREE_VAR (best_regend);                        \
  3135.     FREE_VAR (reg_info);                        \
  3136.     FREE_VAR (reg_dummy);                        \
  3137.     FREE_VAR (reg_info_dummy);                        \
  3138.   } while (0)
  3139. #else /* not REGEX_MALLOC */
  3140. /* Some MIPS systems (at least) want this to free alloca'd storage.  */
  3141. #define FREE_VARIABLES() alloca (0)
  3142. #endif /* not REGEX_MALLOC */
  3143.  
  3144.  
  3145. /* These values must meet several constraints.  They must not be valid
  3146.    register values; since we have a limit of 255 registers (because
  3147.    we use only one byte in the pattern for the register number), we can
  3148.    use numbers larger than 255.  They must differ by 1, because of
  3149.    NUM_FAILURE_ITEMS above.  And the value for the lowest register must
  3150.    be larger than the value for the highest register, so we do not try
  3151.    to actually save any registers when none are active.  */
  3152. #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
  3153. #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
  3154.  
  3155. /* Matching routines.  */
  3156.  
  3157. #ifndef emacs   /* Emacs never uses this.  */
  3158. /* re_match is like re_match_2 except it takes only a single string.  */
  3159.  
  3160. int
  3161. re_match (bufp, string, size, pos, regs)
  3162.      struct re_pattern_buffer *bufp;
  3163.      const char *string;
  3164.      int size, pos;
  3165.      struct re_registers *regs;
  3166.  {
  3167.   return re_match_2 (bufp, NULL, 0, string, size, pos, regs, size); 
  3168. }
  3169. #endif /* not emacs */
  3170.  
  3171.  
  3172. /* re_match_2 matches the compiled pattern in BUFP against the
  3173.    the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
  3174.    and SIZE2, respectively).  We start matching at POS, and stop
  3175.    matching at STOP.
  3176.    
  3177.    If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
  3178.    store offsets for the substring each group matched in REGS.  See the
  3179.    documentation for exactly how many groups we fill.
  3180.  
  3181.    We return -1 if no match, -2 if an internal error (such as the
  3182.    failure stack overflowing).  Otherwise, we return the length of the
  3183.    matched substring.  */
  3184.  
  3185. int
  3186. re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
  3187.      struct re_pattern_buffer *bufp;
  3188.      const char *string1, *string2;
  3189.      int size1, size2;
  3190.      int pos;
  3191.      struct re_registers *regs;
  3192.      int stop;
  3193. {
  3194.   /* General temporaries.  */
  3195.   int mcnt;
  3196.   unsigned char *p1;
  3197.  
  3198.   /* Just past the end of the corresponding string.  */
  3199.   const char *end1, *end2;
  3200.  
  3201.   /* Pointers into string1 and string2, just past the last characters in
  3202.      each to consider matching.  */
  3203.   const char *end_match_1, *end_match_2;
  3204.  
  3205.   /* Where we are in the data, and the end of the current string.  */
  3206.   const char *d, *dend;
  3207.   
  3208.   /* Where we are in the pattern, and the end of the pattern.  */
  3209.   unsigned char *p = bufp->buffer;
  3210.   register unsigned char *pend = p + bufp->used;
  3211.  
  3212.   /* We use this to map every character in the string.  */
  3213.   char *translate = bufp->translate;
  3214.  
  3215.   /* Failure point stack.  Each place that can handle a failure further
  3216.      down the line pushes a failure point on this stack.  It consists of
  3217.      restart, regend, and reg_info for all registers corresponding to
  3218.      the subexpressions we're currently inside, plus the number of such
  3219.      registers, and, finally, two char *'s.  The first char * is where
  3220.      to resume scanning the pattern; the second one is where to resume
  3221.      scanning the strings.  If the latter is zero, the failure point is
  3222.      a ``dummy''; if a failure happens and the failure point is a dummy,
  3223.      it gets discarded and the next next one is tried.  */
  3224.   fail_stack_type fail_stack;
  3225. #ifdef DEBUG
  3226.   static unsigned failure_id = 0;
  3227.   unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
  3228. #endif
  3229.  
  3230.   /* We fill all the registers internally, independent of what we
  3231.      return, for use in backreferences.  The number here includes
  3232.      an element for register zero.  */
  3233.   unsigned num_regs = bufp->re_nsub + 1;
  3234.   
  3235.   /* The currently active registers.  */
  3236.   unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3237.   unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3238.  
  3239.   /* Information on the contents of registers. These are pointers into
  3240.      the input strings; they record just what was matched (on this
  3241.      attempt) by a subexpression part of the pattern, that is, the
  3242.      regnum-th regstart pointer points to where in the pattern we began
  3243.      matching and the regnum-th regend points to right after where we
  3244.      stopped matching the regnum-th subexpression.  (The zeroth register
  3245.      keeps track of what the whole pattern matches.)  */
  3246.   const char **regstart, **regend;
  3247.  
  3248.   /* If a group that's operated upon by a repetition operator fails to
  3249.      match anything, then the register for its start will need to be
  3250.      restored because it will have been set to wherever in the string we
  3251.      are when we last see its open-group operator.  Similarly for a
  3252.      register's end.  */
  3253.   const char **old_regstart, **old_regend;
  3254.  
  3255.   /* The is_active field of reg_info helps us keep track of which (possibly
  3256.      nested) subexpressions we are currently in. The matched_something
  3257.      field of reg_info[reg_num] helps us tell whether or not we have
  3258.      matched any of the pattern so far this time through the reg_num-th
  3259.      subexpression.  These two fields get reset each time through any
  3260.      loop their register is in.  */
  3261.   register_info_type *reg_info; 
  3262.  
  3263.   /* The following record the register info as found in the above
  3264.      variables when we find a match better than any we've seen before. 
  3265.      This happens as we backtrack through the failure points, which in
  3266.      turn happens only if we have not yet matched the entire string. */
  3267.   unsigned best_regs_set = false;
  3268.   const char **best_regstart, **best_regend;
  3269.   
  3270.   /* Logically, this is `best_regend[0]'.  But we don't want to have to
  3271.      allocate space for that if we're not allocating space for anything
  3272.      else (see below).  Also, we never need info about register 0 for
  3273.      any of the other register vectors, and it seems rather a kludge to
  3274.      treat `best_regend' differently than the rest.  So we keep track of
  3275.      the end of the best match so far in a separate variable.  We
  3276.      initialize this to NULL so that when we backtrack the first time
  3277.      and need to test it, it's not garbage.  */
  3278.   const char *match_end = NULL;
  3279.  
  3280.   /* Used when we pop values we don't care about.  */
  3281.   const char **reg_dummy;
  3282.   register_info_type *reg_info_dummy;
  3283.  
  3284. #ifdef DEBUG
  3285.   /* Counts the total number of registers pushed.  */
  3286.   unsigned num_regs_pushed = 0;     
  3287. #endif
  3288.  
  3289.   DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
  3290.   
  3291.   INIT_FAIL_STACK ();
  3292.   
  3293.   /* Do not bother to initialize all the register variables if there are
  3294.      no groups in the pattern, as it takes a fair amount of time.  If
  3295.      there are groups, we include space for register 0 (the whole
  3296.      pattern), even though we never use it, since it simplifies the
  3297.      array indexing.  We should fix this.  */
  3298.   if (bufp->re_nsub)
  3299.     {
  3300.       regstart = REGEX_TALLOC (num_regs, const char *);
  3301.       regend = REGEX_TALLOC (num_regs, const char *);
  3302.       old_regstart = REGEX_TALLOC (num_regs, const char *);
  3303.       old_regend = REGEX_TALLOC (num_regs, const char *);
  3304.       best_regstart = REGEX_TALLOC (num_regs, const char *);
  3305.       best_regend = REGEX_TALLOC (num_regs, const char *);
  3306.       reg_info = REGEX_TALLOC (num_regs, register_info_type);
  3307.       reg_dummy = REGEX_TALLOC (num_regs, const char *);
  3308.       reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
  3309.  
  3310.       if (!(regstart && regend && old_regstart && old_regend && reg_info 
  3311.             && best_regstart && best_regend && reg_dummy && reg_info_dummy)) 
  3312.         {
  3313.           FREE_VARIABLES ();
  3314.           return -2;
  3315.         }
  3316.     }
  3317. #ifdef REGEX_MALLOC
  3318.   else
  3319.     {
  3320.       /* We must initialize all our variables to NULL, so that
  3321.          `FREE_VARIABLES' doesn't try to free them.  */
  3322.       regstart = regend = old_regstart = old_regend = best_regstart
  3323.         = best_regend = reg_dummy = NULL;
  3324.       reg_info = reg_info_dummy = (register_info_type *) NULL;
  3325.     }
  3326. #endif /* REGEX_MALLOC */
  3327.  
  3328.   /* The starting position is bogus.  */
  3329.   if (pos < 0 || pos > size1 + size2)
  3330.     {
  3331.       FREE_VARIABLES ();
  3332.       return -1;
  3333.     }
  3334.     
  3335.   /* Initialize subexpression text positions to -1 to mark ones that no
  3336.      start_memory/stop_memory has been seen for. Also initialize the
  3337.      register information struct.  */
  3338.   for (mcnt = 1; mcnt < num_regs; mcnt++)
  3339.     {
  3340.       regstart[mcnt] = regend[mcnt] 
  3341.         = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
  3342.         
  3343.       REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
  3344.       IS_ACTIVE (reg_info[mcnt]) = 0;
  3345.       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  3346.       EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
  3347.     }
  3348.   
  3349.   /* We move `string1' into `string2' if the latter's empty -- but not if
  3350.      `string1' is null.  */
  3351.   if (size2 == 0 && string1 != NULL)
  3352.     {
  3353.       string2 = string1;
  3354.       size2 = size1;
  3355.       string1 = 0;
  3356.       size1 = 0;
  3357.     }
  3358.   end1 = string1 + size1;
  3359.   end2 = string2 + size2;
  3360.  
  3361.   /* Compute where to stop matching, within the two strings.  */
  3362.   if (stop <= size1)
  3363.     {
  3364.       end_match_1 = string1 + stop;
  3365.       end_match_2 = string2;
  3366.     }
  3367.   else
  3368.     {
  3369.       end_match_1 = end1;
  3370.       end_match_2 = string2 + stop - size1;
  3371.     }
  3372.  
  3373.   /* `p' scans through the pattern as `d' scans through the data. 
  3374.      `dend' is the end of the input string that `d' points within.  `d'
  3375.      is advanced into the following input string whenever necessary, but
  3376.      this happens before fetching; therefore, at the beginning of the
  3377.      loop, `d' can be pointing at the end of a string, but it cannot
  3378.      equal `string2'.  */
  3379.   if (size1 > 0 && pos <= size1)
  3380.     {
  3381.       d = string1 + pos;
  3382.       dend = end_match_1;
  3383.     }
  3384.   else
  3385.     {
  3386.       d = string2 + pos - size1;
  3387.       dend = end_match_2;
  3388.     }
  3389.  
  3390.   DEBUG_PRINT1 ("The compiled pattern is: ");
  3391.   DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
  3392.   DEBUG_PRINT1 ("The string to match is: `");
  3393.   DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
  3394.   DEBUG_PRINT1 ("'\n");
  3395.   
  3396.   /* This loops over pattern commands.  It exits by returning from the
  3397.      function if the match is complete, or it drops through if the match
  3398.      fails at this starting point in the input data.  */
  3399.   for (;;)
  3400.     {
  3401.       DEBUG_PRINT2 ("\n0x%x: ", p);
  3402.  
  3403.       if (p == pend)
  3404.     { /* End of pattern means we might have succeeded.  */
  3405.           DEBUG_PRINT1 ("end of pattern ... ");
  3406.           
  3407.       /* If we haven't matched the entire string, and we want the
  3408.              longest match, try backtracking.  */
  3409.           if (d != end_match_2)
  3410.         {
  3411.               DEBUG_PRINT1 ("backtracking.\n");
  3412.               
  3413.               if (!FAIL_STACK_EMPTY ())
  3414.                 { /* More failure points to try.  */
  3415.                   boolean same_str_p = (FIRST_STRING_P (match_end) 
  3416.                                 == MATCHING_IN_FIRST_STRING);
  3417.  
  3418.                   /* If exceeds best match so far, save it.  */
  3419.                   if (!best_regs_set
  3420.                       || (same_str_p && d > match_end)
  3421.                       || (!same_str_p && !MATCHING_IN_FIRST_STRING))
  3422.                     {
  3423.                       best_regs_set = true;
  3424.                       match_end = d;
  3425.                       
  3426.                       DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
  3427.                       
  3428.                       for (mcnt = 1; mcnt < num_regs; mcnt++)
  3429.                         {
  3430.                           best_regstart[mcnt] = regstart[mcnt];
  3431.                           best_regend[mcnt] = regend[mcnt];
  3432.                         }
  3433.                     }
  3434.                   goto fail;           
  3435.                 }
  3436.  
  3437.               /* If no failure points, don't restore garbage.  */
  3438.               else if (best_regs_set)   
  3439.                 {
  3440.               restore_best_regs:
  3441.                   /* Restore best match.  It may happen that `dend ==
  3442.                      end_match_1' while the restored d is in string2.
  3443.                      For example, the pattern `x.*y.*z' against the
  3444.                      strings `x-' and `y-z-', if the two strings are
  3445.                      not consecutive in memory.  */
  3446.                   DEBUG_PRINT1 ("Restoring best registers.\n");
  3447.                   
  3448.                   d = match_end;
  3449.                   dend = ((d >= string1 && d <= end1)
  3450.                    ? end_match_1 : end_match_2);
  3451.  
  3452.           for (mcnt = 1; mcnt < num_regs; mcnt++)
  3453.             {
  3454.               regstart[mcnt] = best_regstart[mcnt];
  3455.               regend[mcnt] = best_regend[mcnt];
  3456.             }
  3457.                 }
  3458.             } /* d != end_match_2 */
  3459.  
  3460.           DEBUG_PRINT1 ("Accepting match.\n");
  3461.  
  3462.           /* If caller wants register contents data back, do it.  */
  3463.           if (regs && !bufp->no_sub)
  3464.         {
  3465.               /* Have the register data arrays been allocated?  */
  3466.               if (bufp->regs_allocated == REGS_UNALLOCATED)
  3467.                 { /* No.  So allocate them with malloc.  We need one
  3468.                      extra element beyond `num_regs' for the `-1' marker
  3469.                      GNU code uses.  */
  3470.                   regs->num_regs = MAX (RE_NREGS, num_regs + 1);
  3471.                   regs->start = TALLOC (regs->num_regs, regoff_t);
  3472.                   regs->end = TALLOC (regs->num_regs, regoff_t);
  3473.                   if (regs->start == NULL || regs->end == NULL)
  3474.                     return -2;
  3475.                   bufp->regs_allocated = REGS_REALLOCATE;
  3476.                 }
  3477.               else if (bufp->regs_allocated == REGS_REALLOCATE)
  3478.                 { /* Yes.  If we need more elements than were already
  3479.                      allocated, reallocate them.  If we need fewer, just
  3480.                      leave it alone.  */
  3481.                   if (regs->num_regs < num_regs + 1)
  3482.                     {
  3483.                       regs->num_regs = num_regs + 1;
  3484.                       RETALLOC (regs->start, regs->num_regs, regoff_t);
  3485.                       RETALLOC (regs->end, regs->num_regs, regoff_t);
  3486.                       if (regs->start == NULL || regs->end == NULL)
  3487.                         return -2;
  3488.                     }
  3489.                 }
  3490.               else
  3491.         {
  3492.           /* These braces fend off a "empty body in an else-statement"
  3493.              warning under GCC when assert expands to nothing.  */
  3494.           assert (bufp->regs_allocated == REGS_FIXED);
  3495.         }
  3496.  
  3497.               /* Convert the pointer data in `regstart' and `regend' to
  3498.                  indices.  Register zero has to be set differently,
  3499.                  since we haven't kept track of any info for it.  */
  3500.               if (regs->num_regs > 0)
  3501.                 {
  3502.                   regs->start[0] = pos;
  3503.                   regs->end[0] = (MATCHING_IN_FIRST_STRING ? d - string1
  3504.                       : d - string2 + size1);
  3505.                 }
  3506.               
  3507.               /* Go through the first `min (num_regs, regs->num_regs)'
  3508.                  registers, since that is all we initialized.  */
  3509.           for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
  3510.         {
  3511.                   if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
  3512.                     regs->start[mcnt] = regs->end[mcnt] = -1;
  3513.                   else
  3514.                     {
  3515.               regs->start[mcnt] = POINTER_TO_OFFSET (regstart[mcnt]);
  3516.                       regs->end[mcnt] = POINTER_TO_OFFSET (regend[mcnt]);
  3517.                     }
  3518.         }
  3519.               
  3520.               /* If the regs structure we return has more elements than
  3521.                  were in the pattern, set the extra elements to -1.  If
  3522.                  we (re)allocated the registers, this is the case,
  3523.                  because we always allocate enough to have at least one
  3524.                  -1 at the end.  */
  3525.               for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
  3526.                 regs->start[mcnt] = regs->end[mcnt] = -1;
  3527.         } /* regs && !bufp->no_sub */
  3528.  
  3529.           FREE_VARIABLES ();
  3530.           DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
  3531.                         nfailure_points_pushed, nfailure_points_popped,
  3532.                         nfailure_points_pushed - nfailure_points_popped);
  3533.           DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
  3534.  
  3535.           mcnt = d - pos - (MATCHING_IN_FIRST_STRING 
  3536.                 ? string1 
  3537.                 : string2 - size1);
  3538.  
  3539.           DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
  3540.  
  3541.           return mcnt;
  3542.         }
  3543.  
  3544.       /* Otherwise match next pattern command.  */
  3545. #ifdef SWITCH_ENUM_BUG
  3546.       switch ((int) ((re_opcode_t) *p++))
  3547. #else
  3548.       switch ((re_opcode_t) *p++)
  3549. #endif
  3550.     {
  3551.         /* Ignore these.  Used to ignore the n of succeed_n's which
  3552.            currently have n == 0.  */
  3553.         case no_op:
  3554.           DEBUG_PRINT1 ("EXECUTING no_op.\n");
  3555.           break;
  3556.  
  3557.  
  3558.         /* Match the next n pattern characters exactly.  The following
  3559.            byte in the pattern defines n, and the n bytes after that
  3560.            are the characters to match.  */
  3561.     case exactn:
  3562.       mcnt = *p++;
  3563.           DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
  3564.  
  3565.           /* This is written out as an if-else so we don't waste time
  3566.              testing `translate' inside the loop.  */
  3567.           if (translate)
  3568.         {
  3569.           do
  3570.         {
  3571.           PREFETCH ();
  3572.           if (translate[(unsigned char) *d++] != (char) *p++)
  3573.                     goto fail;
  3574.         }
  3575.           while (--mcnt);
  3576.         }
  3577.       else
  3578.         {
  3579.           do
  3580.         {
  3581.           PREFETCH ();
  3582.           if (*d++ != (char) *p++) goto fail;
  3583.         }
  3584.           while (--mcnt);
  3585.         }
  3586.       SET_REGS_MATCHED ();
  3587.           break;
  3588.  
  3589.  
  3590.         /* Match any character except possibly a newline or a null.  */
  3591.     case anychar:
  3592.           DEBUG_PRINT1 ("EXECUTING anychar.\n");
  3593.  
  3594.           PREFETCH ();
  3595.  
  3596.           if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
  3597.               || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
  3598.         goto fail;
  3599.  
  3600.           SET_REGS_MATCHED ();
  3601.           DEBUG_PRINT2 ("  Matched `%d'.\n", *d);
  3602.           d++;
  3603.       break;
  3604.  
  3605.  
  3606.     case charset:
  3607.     case charset_not:
  3608.       {
  3609.         register unsigned char c;
  3610.         boolean not = (re_opcode_t) *(p - 1) == charset_not;
  3611.  
  3612.             DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
  3613.  
  3614.         PREFETCH ();
  3615.         c = TRANSLATE (*d); /* The character to match.  */
  3616.  
  3617.             /* Cast to `unsigned' instead of `unsigned char' in case the
  3618.                bit list is a full 32 bytes long.  */
  3619.         if (c < (unsigned) (*p * BYTEWIDTH)
  3620.         && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  3621.           not = !not;
  3622.  
  3623.         p += 1 + *p;
  3624.  
  3625.         if (!not) goto fail;
  3626.             
  3627.         SET_REGS_MATCHED ();
  3628.             d++;
  3629.         break;
  3630.       }
  3631.  
  3632.  
  3633.         /* The beginning of a group is represented by start_memory.
  3634.            The arguments are the register number in the next byte, and the
  3635.            number of groups inner to this one in the next.  The text
  3636.            matched within the group is recorded (in the internal
  3637.            registers data structure) under the register number.  */
  3638.         case start_memory:
  3639.       DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
  3640.  
  3641.           /* Find out if this group can match the empty string.  */
  3642.       p1 = p;        /* To send to group_match_null_string_p.  */
  3643.           
  3644.           if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
  3645.             REG_MATCH_NULL_STRING_P (reg_info[*p]) 
  3646.               = group_match_null_string_p (&p1, pend, reg_info);
  3647.  
  3648.           /* Save the position in the string where we were the last time
  3649.              we were at this open-group operator in case the group is
  3650.              operated upon by a repetition operator, e.g., with `(a*)*b'
  3651.              against `ab'; then we want to ignore where we are now in
  3652.              the string in case this attempt to match fails.  */
  3653.           old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  3654.                              ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
  3655.                              : regstart[*p];
  3656.       DEBUG_PRINT2 ("  old_regstart: %d\n", 
  3657.              POINTER_TO_OFFSET (old_regstart[*p]));
  3658.  
  3659.           regstart[*p] = d;
  3660.       DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
  3661.  
  3662.           IS_ACTIVE (reg_info[*p]) = 1;
  3663.           MATCHED_SOMETHING (reg_info[*p]) = 0;
  3664.           
  3665.           /* This is the new highest active register.  */
  3666.           highest_active_reg = *p;
  3667.           
  3668.           /* If nothing was active before, this is the new lowest active
  3669.              register.  */
  3670.           if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  3671.             lowest_active_reg = *p;
  3672.  
  3673.           /* Move past the register number and inner group count.  */
  3674.           p += 2;
  3675.           break;
  3676.  
  3677.  
  3678.         /* The stop_memory opcode represents the end of a group.  Its
  3679.            arguments are the same as start_memory's: the register
  3680.            number, and the number of inner groups.  */
  3681.     case stop_memory:
  3682.       DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
  3683.              
  3684.           /* We need to save the string position the last time we were at
  3685.              this close-group operator in case the group is operated
  3686.              upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
  3687.              against `aba'; then we want to ignore where we are now in
  3688.              the string in case this attempt to match fails.  */
  3689.           old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
  3690.                            ? REG_UNSET (regend[*p]) ? d : regend[*p]
  3691.                : regend[*p];
  3692.       DEBUG_PRINT2 ("      old_regend: %d\n", 
  3693.              POINTER_TO_OFFSET (old_regend[*p]));
  3694.  
  3695.           regend[*p] = d;
  3696.       DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
  3697.  
  3698.           /* This register isn't active anymore.  */
  3699.           IS_ACTIVE (reg_info[*p]) = 0;
  3700.           
  3701.           /* If this was the only register active, nothing is active
  3702.              anymore.  */
  3703.           if (lowest_active_reg == highest_active_reg)
  3704.             {
  3705.               lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3706.               highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3707.             }
  3708.           else
  3709.             { /* We must scan for the new highest active register, since
  3710.                  it isn't necessarily one less than now: consider
  3711.                  (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
  3712.                  new highest active register is 1.  */
  3713.               unsigned char r = *p - 1;
  3714.               while (r > 0 && !IS_ACTIVE (reg_info[r]))
  3715.                 r--;
  3716.               
  3717.               /* If we end up at register zero, that means that we saved
  3718.                  the registers as the result of an `on_failure_jump', not
  3719.                  a `start_memory', and we jumped to past the innermost
  3720.                  `stop_memory'.  For example, in ((.)*) we save
  3721.                  registers 1 and 2 as a result of the *, but when we pop
  3722.                  back to the second ), we are at the stop_memory 1.
  3723.                  Thus, nothing is active.  */
  3724.           if (r == 0)
  3725.                 {
  3726.                   lowest_active_reg = NO_LOWEST_ACTIVE_REG;
  3727.                   highest_active_reg = NO_HIGHEST_ACTIVE_REG;
  3728.                 }
  3729.               else
  3730.                 highest_active_reg = r;
  3731.             }
  3732.           
  3733.           /* If just failed to match something this time around with a
  3734.              group that's operated on by a repetition operator, try to
  3735.              force exit from the ``loop'', and restore the register
  3736.              information for this group that we had before trying this
  3737.              last match.  */
  3738.           if ((!MATCHED_SOMETHING (reg_info[*p])
  3739.                || (re_opcode_t) p[-3] == start_memory)
  3740.           && (p + 2) < pend)              
  3741.             {
  3742.               boolean is_a_jump_n = false;
  3743.               
  3744.               p1 = p + 2;
  3745.               mcnt = 0;
  3746.               switch ((re_opcode_t) *p1++)
  3747.                 {
  3748.                   case jump_n:
  3749.             is_a_jump_n = true;
  3750.                   case pop_failure_jump:
  3751.           case maybe_pop_jump:
  3752.           case jump:
  3753.           case dummy_failure_jump:
  3754.                     EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3755.             if (is_a_jump_n)
  3756.               p1 += 2;
  3757.                     break;
  3758.                   
  3759.                   default:
  3760.                     /* do nothing */ ;
  3761.                 }
  3762.           p1 += mcnt;
  3763.         
  3764.               /* If the next operation is a jump backwards in the pattern
  3765.              to an on_failure_jump right before the start_memory
  3766.                  corresponding to this stop_memory, exit from the loop
  3767.                  by forcing a failure after pushing on the stack the
  3768.                  on_failure_jump's jump in the pattern, and d.  */
  3769.               if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
  3770.                   && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
  3771.         {
  3772.                   /* If this group ever matched anything, then restore
  3773.                      what its registers were before trying this last
  3774.                      failed match, e.g., with `(a*)*b' against `ab' for
  3775.                      regstart[1], and, e.g., with `((a*)*(b*)*)*'
  3776.                      against `aba' for regend[3].
  3777.                      
  3778.                      Also restore the registers for inner groups for,
  3779.                      e.g., `((a*)(b*))*' against `aba' (register 3 would
  3780.                      otherwise get trashed).  */
  3781.                      
  3782.                   if (EVER_MATCHED_SOMETHING (reg_info[*p]))
  3783.             {
  3784.               unsigned r; 
  3785.         
  3786.                       EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
  3787.                       
  3788.               /* Restore this and inner groups' (if any) registers.  */
  3789.                       for (r = *p; r < *p + *(p + 1); r++)
  3790.                         {
  3791.                           regstart[r] = old_regstart[r];
  3792.  
  3793.                           /* xx why this test?  */
  3794.                           if ((int) old_regend[r] >= (int) regstart[r])
  3795.                             regend[r] = old_regend[r];
  3796.                         }     
  3797.                     }
  3798.           p1++;
  3799.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  3800.                   PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
  3801.  
  3802.                   goto fail;
  3803.                 }
  3804.             }
  3805.           
  3806.           /* Move past the register number and the inner group count.  */
  3807.           p += 2;
  3808.           break;
  3809.  
  3810.  
  3811.     /* \<digit> has been turned into a `duplicate' command which is
  3812.            followed by the numeric value of <digit> as the register number.  */
  3813.         case duplicate:
  3814.       {
  3815.         register const char *d2, *dend2;
  3816.         int regno = *p++;   /* Get which register to match against.  */
  3817.         DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
  3818.  
  3819.         /* Can't back reference a group which we've never matched.  */
  3820.             if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
  3821.               goto fail;
  3822.               
  3823.             /* Where in input to try to start matching.  */
  3824.             d2 = regstart[regno];
  3825.             
  3826.             /* Where to stop matching; if both the place to start and
  3827.                the place to stop matching are in the same string, then
  3828.                set to the place to stop, otherwise, for now have to use
  3829.                the end of the first string.  */
  3830.  
  3831.             dend2 = ((FIRST_STRING_P (regstart[regno]) 
  3832.               == FIRST_STRING_P (regend[regno]))
  3833.              ? regend[regno] : end_match_1);
  3834.         for (;;)
  3835.           {
  3836.         /* If necessary, advance to next segment in register
  3837.                    contents.  */
  3838.         while (d2 == dend2)
  3839.           {
  3840.             if (dend2 == end_match_2) break;
  3841.             if (dend2 == regend[regno]) break;
  3842.  
  3843.                     /* End of string1 => advance to string2. */
  3844.                     d2 = string2;
  3845.                     dend2 = regend[regno];
  3846.           }
  3847.         /* At end of register contents => success */
  3848.         if (d2 == dend2) break;
  3849.  
  3850.         /* If necessary, advance to next segment in data.  */
  3851.         PREFETCH ();
  3852.  
  3853.         /* How many characters left in this segment to match.  */
  3854.         mcnt = dend - d;
  3855.                 
  3856.         /* Want how many consecutive characters we can match in
  3857.                    one shot, so, if necessary, adjust the count.  */
  3858.                 if (mcnt > dend2 - d2)
  3859.           mcnt = dend2 - d2;
  3860.                   
  3861.         /* Compare that many; failure if mismatch, else move
  3862.                    past them.  */
  3863.         if (translate 
  3864.                     ? bcmp_translate (d, d2, mcnt, translate) 
  3865.                     : bcmp (d, d2, mcnt))
  3866.           goto fail;
  3867.         d += mcnt, d2 += mcnt;
  3868.           }
  3869.       }
  3870.       break;
  3871.  
  3872.  
  3873.         /* begline matches the empty string at the beginning of the string
  3874.            (unless `not_bol' is set in `bufp'), and, if
  3875.            `newline_anchor' is set, after newlines.  */
  3876.     case begline:
  3877.           DEBUG_PRINT1 ("EXECUTING begline.\n");
  3878.           
  3879.           if (AT_STRINGS_BEG (d))
  3880.             {
  3881.               if (!bufp->not_bol) break;
  3882.             }
  3883.           else if (d[-1] == '\n' && bufp->newline_anchor)
  3884.             {
  3885.               break;
  3886.             }
  3887.           /* In all other cases, we fail.  */
  3888.           goto fail;
  3889.  
  3890.  
  3891.         /* endline is the dual of begline.  */
  3892.     case endline:
  3893.           DEBUG_PRINT1 ("EXECUTING endline.\n");
  3894.  
  3895.           if (AT_STRINGS_END (d))
  3896.             {
  3897.               if (!bufp->not_eol) break;
  3898.             }
  3899.           
  3900.           /* We have to ``prefetch'' the next character.  */
  3901.           else if ((d == end1 ? *string2 : *d) == '\n'
  3902.                    && bufp->newline_anchor)
  3903.             {
  3904.               break;
  3905.             }
  3906.           goto fail;
  3907.  
  3908.  
  3909.     /* Match at the very beginning of the data.  */
  3910.         case begbuf:
  3911.           DEBUG_PRINT1 ("EXECUTING begbuf.\n");
  3912.           if (AT_STRINGS_BEG (d))
  3913.             break;
  3914.           goto fail;
  3915.  
  3916.  
  3917.     /* Match at the very end of the data.  */
  3918.         case endbuf:
  3919.           DEBUG_PRINT1 ("EXECUTING endbuf.\n");
  3920.       if (AT_STRINGS_END (d))
  3921.         break;
  3922.           goto fail;
  3923.  
  3924.  
  3925.         /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
  3926.            pushes NULL as the value for the string on the stack.  Then
  3927.            `pop_failure_point' will keep the current value for the
  3928.            string, instead of restoring it.  To see why, consider
  3929.            matching `foo\nbar' against `.*\n'.  The .* matches the foo;
  3930.            then the . fails against the \n.  But the next thing we want
  3931.            to do is match the \n against the \n; if we restored the
  3932.            string value, we would be back at the foo.
  3933.            
  3934.            Because this is used only in specific cases, we don't need to
  3935.            check all the things that `on_failure_jump' does, to make
  3936.            sure the right things get saved on the stack.  Hence we don't
  3937.            share its code.  The only reason to push anything on the
  3938.            stack at all is that otherwise we would have to change
  3939.            `anychar's code to do something besides goto fail in this
  3940.            case; that seems worse than this.  */
  3941.         case on_failure_keep_string_jump:
  3942.           DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
  3943.           
  3944.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3945.           DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
  3946.  
  3947.           PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
  3948.           break;
  3949.  
  3950.  
  3951.     /* Uses of on_failure_jump:
  3952.         
  3953.            Each alternative starts with an on_failure_jump that points
  3954.            to the beginning of the next alternative.  Each alternative
  3955.            except the last ends with a jump that in effect jumps past
  3956.            the rest of the alternatives.  (They really jump to the
  3957.            ending jump of the following alternative, because tensioning
  3958.            these jumps is a hassle.)
  3959.  
  3960.            Repeats start with an on_failure_jump that points past both
  3961.            the repetition text and either the following jump or
  3962.            pop_failure_jump back to this on_failure_jump.  */
  3963.     case on_failure_jump:
  3964.         on_failure:
  3965.           DEBUG_PRINT1 ("EXECUTING on_failure_jump");
  3966.  
  3967.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  3968.           DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
  3969.  
  3970.           /* If this on_failure_jump comes right before a group (i.e.,
  3971.              the original * applied to a group), save the information
  3972.              for that group and all inner ones, so that if we fail back
  3973.              to this point, the group's information will be correct.
  3974.              For example, in \(a*\)*\1, we need the preceding group,
  3975.              and in \(\(a*\)b*\)\2, we need the inner group.  */
  3976.  
  3977.           /* We can't use `p' to check ahead because we push
  3978.              a failure point to `p + mcnt' after we do this.  */
  3979.           p1 = p;
  3980.  
  3981.           /* We need to skip no_op's before we look for the
  3982.              start_memory in case this on_failure_jump is happening as
  3983.              the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
  3984.              against aba.  */
  3985.           while (p1 < pend && (re_opcode_t) *p1 == no_op)
  3986.             p1++;
  3987.  
  3988.           if (p1 < pend && (re_opcode_t) *p1 == start_memory)
  3989.             {
  3990.               /* We have a new highest active register now.  This will
  3991.                  get reset at the start_memory we are about to get to,
  3992.                  but we will have saved all the registers relevant to
  3993.                  this repetition op, as described above.  */
  3994.               highest_active_reg = *(p1 + 1) + *(p1 + 2);
  3995.               if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
  3996.                 lowest_active_reg = *(p1 + 1);
  3997.             }
  3998.  
  3999.           DEBUG_PRINT1 (":\n");
  4000.           PUSH_FAILURE_POINT (p + mcnt, d, -2);
  4001.           break;
  4002.  
  4003.  
  4004.         /* A smart repeat ends with `maybe_pop_jump'.
  4005.        We change it to either `pop_failure_jump' or `jump'.  */
  4006.         case maybe_pop_jump:
  4007.           EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4008.           DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
  4009.           {
  4010.         register unsigned char *p2 = p;
  4011.  
  4012.             /* Compare the beginning of the repeat with what in the
  4013.                pattern follows its end. If we can establish that there
  4014.                is nothing that they would both match, i.e., that we
  4015.                would have to backtrack because of (as in, e.g., `a*a')
  4016.                then we can change to pop_failure_jump, because we'll
  4017.                never have to backtrack.
  4018.                
  4019.                This is not true in the case of alternatives: in
  4020.                `(a|ab)*' we do need to backtrack to the `ab' alternative
  4021.                (e.g., if the string was `ab').  But instead of trying to
  4022.                detect that here, the alternative has put on a dummy
  4023.                failure point which is what we will end up popping.  */
  4024.  
  4025.         /* Skip over open/close-group commands.  */
  4026.         while (p2 + 2 < pend
  4027.            && ((re_opcode_t) *p2 == stop_memory
  4028.                || (re_opcode_t) *p2 == start_memory))
  4029.           p2 += 3;            /* Skip over args, too.  */
  4030.  
  4031.             /* If we're at the end of the pattern, we can change.  */
  4032.             if (p2 == pend)
  4033.           {
  4034.         /* Consider what happens when matching ":\(.*\)"
  4035.            against ":/".  I don't really understand this code
  4036.            yet.  */
  4037.               p[-3] = (unsigned char) pop_failure_jump;
  4038.                 DEBUG_PRINT1
  4039.                   ("  End of pattern: change to `pop_failure_jump'.\n");
  4040.               }
  4041.  
  4042.             else if ((re_opcode_t) *p2 == exactn
  4043.              || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
  4044.           {
  4045.         register unsigned char c
  4046.                   = *p2 == (unsigned char) endline ? '\n' : p2[2];
  4047.         p1 = p + mcnt;
  4048.  
  4049.                 /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
  4050.                    to the `maybe_finalize_jump' of this case.  Examine what 
  4051.                    follows.  */
  4052.                 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
  4053.                   {
  4054.               p[-3] = (unsigned char) pop_failure_jump;
  4055.                     DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
  4056.                                   c, p1[5]);
  4057.                   }
  4058.                   
  4059.         else if ((re_opcode_t) p1[3] == charset
  4060.              || (re_opcode_t) p1[3] == charset_not)
  4061.           {
  4062.             int not = (re_opcode_t) p1[3] == charset_not;
  4063.                     
  4064.             if (c < (unsigned char) (p1[4] * BYTEWIDTH)
  4065.             && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
  4066.               not = !not;
  4067.  
  4068.                     /* `not' is equal to 1 if c would match, which means
  4069.                         that we can't change to pop_failure_jump.  */
  4070.             if (!not)
  4071.                       {
  4072.                   p[-3] = (unsigned char) pop_failure_jump;
  4073.                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
  4074.                       }
  4075.           }
  4076.           }
  4077.       }
  4078.       p -= 2;        /* Point at relative address again.  */
  4079.       if ((re_opcode_t) p[-1] != pop_failure_jump)
  4080.         {
  4081.           p[-1] = (unsigned char) jump;
  4082.               DEBUG_PRINT1 ("  Match => jump.\n");
  4083.           goto unconditional_jump;
  4084.         }
  4085.         /* Note fall through.  */
  4086.  
  4087.  
  4088.     /* The end of a simple repeat has a pop_failure_jump back to
  4089.            its matching on_failure_jump, where the latter will push a
  4090.            failure point.  The pop_failure_jump takes off failure
  4091.            points put on by this pop_failure_jump's matching
  4092.            on_failure_jump; we got through the pattern to here from the
  4093.            matching on_failure_jump, so didn't fail.  */
  4094.         case pop_failure_jump:
  4095.           {
  4096.             /* We need to pass separate storage for the lowest and
  4097.                highest registers, even though we don't care about the
  4098.                actual values.  Otherwise, we will restore only one
  4099.                register from the stack, since lowest will == highest in
  4100.                `pop_failure_point'.  */
  4101.             unsigned dummy_low_reg, dummy_high_reg;
  4102.             unsigned char *pdummy;
  4103.             const char *sdummy;
  4104.  
  4105.             DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
  4106.             POP_FAILURE_POINT (sdummy, pdummy,
  4107.                                dummy_low_reg, dummy_high_reg,
  4108.                                reg_dummy, reg_dummy, reg_info_dummy);
  4109.  
  4110.         if (sdummy != pdummy)
  4111.         sdummy = pdummy; /* stop error */
  4112.           }
  4113.           /* Note fall through.  */
  4114.  
  4115.           
  4116.         /* Unconditionally jump (without popping any failure points).  */
  4117.         case jump:
  4118.     unconditional_jump:
  4119.       EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
  4120.           DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
  4121.       p += mcnt;                /* Do the jump.  */
  4122.           DEBUG_PRINT2 ("(to 0x%x).\n", p);
  4123.       break;
  4124.  
  4125.     
  4126.         /* We need this opcode so we can detect where alternatives end
  4127.            in `group_match_null_string_p' et al.  */
  4128.         case jump_past_alt:
  4129.           DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
  4130.           goto unconditional_jump;
  4131.  
  4132.  
  4133.         /* Normally, the on_failure_jump pushes a failure point, which
  4134.            then gets popped at pop_failure_jump.  We will end up at
  4135.            pop_failure_jump, also, and with a pattern of, say, `a+', we
  4136.            are skipping over the on_failure_jump, so we have to push
  4137.            something meaningless for pop_failure_jump to pop.  */
  4138.         case dummy_failure_jump:
  4139.           DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
  4140.           /* It doesn't matter what we push for the string here.  What
  4141.              the code at `fail' tests is the value for the pattern.  */
  4142.           PUSH_FAILURE_POINT (0, 0, -2);
  4143.           goto unconditional_jump;
  4144.  
  4145.  
  4146.         /* At the end of an alternative, we need to push a dummy failure
  4147.            point in case we are followed by a `pop_failure_jump', because
  4148.            we don't want the failure point for the alternative to be
  4149.            popped.  For example, matching `(a|ab)*' against `aab'
  4150.            requires that we match the `ab' alternative.  */
  4151.         case push_dummy_failure:
  4152.           DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
  4153.           /* See comments just above at `dummy_failure_jump' about the
  4154.              two zeroes.  */
  4155.           PUSH_FAILURE_POINT (0, 0, -2);
  4156.           break;
  4157.  
  4158.         /* Have to succeed matching what follows at least n times.
  4159.            After that, handle like `on_failure_jump'.  */
  4160.         case succeed_n: 
  4161.           EXTRACT_NUMBER (mcnt, p + 2);
  4162.           DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
  4163.  
  4164.           assert (mcnt >= 0);
  4165.           /* Originally, this is how many times we HAVE to succeed.  */
  4166.           if (mcnt > 0)
  4167.             {
  4168.                mcnt--;
  4169.            p += 2;
  4170.                STORE_NUMBER_AND_INCR (p, mcnt);
  4171.                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p, mcnt);
  4172.             }
  4173.       else if (mcnt == 0)
  4174.             {
  4175.               DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n", p+2);
  4176.           p[2] = (unsigned char) no_op;
  4177.               p[3] = (unsigned char) no_op;
  4178.               goto on_failure;
  4179.             }
  4180.           break;
  4181.         
  4182.         case jump_n: 
  4183.           EXTRACT_NUMBER (mcnt, p + 2);
  4184.           DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
  4185.  
  4186.           /* Originally, this is how many times we CAN jump.  */
  4187.           if (mcnt)
  4188.             {
  4189.                mcnt--;
  4190.                STORE_NUMBER (p + 2, mcnt);
  4191.            goto unconditional_jump;         
  4192.             }
  4193.           /* If don't have to jump any more, skip over the rest of command.  */
  4194.       else      
  4195.         p += 4;             
  4196.           break;
  4197.         
  4198.     case set_number_at:
  4199.       {
  4200.             DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
  4201.  
  4202.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4203.             p1 = p + mcnt;
  4204.             EXTRACT_NUMBER_AND_INCR (mcnt, p);
  4205.             DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
  4206.         STORE_NUMBER (p1, mcnt);
  4207.             break;
  4208.           }
  4209.  
  4210.         case wordbound:
  4211.           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
  4212.           if (AT_WORD_BOUNDARY (d))
  4213.         break;
  4214.           goto fail;
  4215.  
  4216.     case notwordbound:
  4217.           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
  4218.       if (AT_WORD_BOUNDARY (d))
  4219.         goto fail;
  4220.           break;
  4221.  
  4222.     case wordbeg:
  4223.           DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
  4224.       if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
  4225.         break;
  4226.           goto fail;
  4227.  
  4228.     case wordend:
  4229.           DEBUG_PRINT1 ("EXECUTING wordend.\n");
  4230.       if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
  4231.               && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
  4232.         break;
  4233.           goto fail;
  4234.  
  4235. #ifdef emacs
  4236. #ifdef emacs19
  4237.       case before_dot:
  4238.           DEBUG_PRINT1 ("EXECUTING before_dot.\n");
  4239.        if (PTR_CHAR_POS ((unsigned char *) d) >= point)
  4240.           goto fail;
  4241.         break;
  4242.   
  4243.       case at_dot:
  4244.           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
  4245.        if (PTR_CHAR_POS ((unsigned char *) d) != point)
  4246.           goto fail;
  4247.         break;
  4248.   
  4249.       case after_dot:
  4250.           DEBUG_PRINT1 ("EXECUTING after_dot.\n");
  4251.           if (PTR_CHAR_POS ((unsigned char *) d) <= point)
  4252.           goto fail;
  4253.         break;
  4254. #else /* not emacs19 */
  4255.     case at_dot:
  4256.           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
  4257.       if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
  4258.         goto fail;
  4259.       break;
  4260. #endif /* not emacs19 */
  4261.  
  4262.     case syntaxspec:
  4263.           DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
  4264.       mcnt = *p++;
  4265.       goto matchsyntax;
  4266.  
  4267.         case wordchar:
  4268.           DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
  4269.       mcnt = (int) Sword;
  4270.         matchsyntax:
  4271.       PREFETCH ();
  4272.       if (SYNTAX (*d++) != (enum syntaxcode) mcnt)
  4273.             goto fail;
  4274.           SET_REGS_MATCHED ();
  4275.       break;
  4276.  
  4277.     case notsyntaxspec:
  4278.           DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
  4279.       mcnt = *p++;
  4280.       goto matchnotsyntax;
  4281.  
  4282.         case notwordchar:
  4283.           DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
  4284.       mcnt = (int) Sword;
  4285.         matchnotsyntax:
  4286.       PREFETCH ();
  4287.       if (SYNTAX (*d++) == (enum syntaxcode) mcnt)
  4288.             goto fail;
  4289.       SET_REGS_MATCHED ();
  4290.           break;
  4291.  
  4292. #else /* not emacs */
  4293.     case wordchar:
  4294.           DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
  4295.       PREFETCH ();
  4296.           if (!WORDCHAR_P (d))
  4297.             goto fail;
  4298.       SET_REGS_MATCHED ();
  4299.           d++;
  4300.       break;
  4301.       
  4302.     case notwordchar:
  4303.           DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
  4304.       PREFETCH ();
  4305.       if (WORDCHAR_P (d))
  4306.             goto fail;
  4307.           SET_REGS_MATCHED ();
  4308.           d++;
  4309.       break;
  4310. #endif /* not emacs */
  4311.           
  4312.         default:
  4313.           abort ();
  4314.     }
  4315.       continue;  /* Successfully executed one pattern command; keep going.  */
  4316.  
  4317.  
  4318.     /* We goto here if a matching operation fails. */
  4319.     fail:
  4320.       if (!FAIL_STACK_EMPTY ())
  4321.     { /* A restart point is known.  Restore to that state.  */
  4322.           DEBUG_PRINT1 ("\nFAIL:\n");
  4323.           POP_FAILURE_POINT (d, p,
  4324.                              lowest_active_reg, highest_active_reg,
  4325.                              regstart, regend, reg_info);
  4326.  
  4327.           /* If this failure point is a dummy, try the next one.  */
  4328.           if (!p)
  4329.         goto fail;
  4330.  
  4331.           /* If we failed to the end of the pattern, don't examine *p.  */
  4332.       assert (p <= pend);
  4333.           if (p < pend)
  4334.             {
  4335.               boolean is_a_jump_n = false;
  4336.               
  4337.               /* If failed to a backwards jump that's part of a repetition
  4338.                  loop, need to pop this failure point and use the next one.  */
  4339.               switch ((re_opcode_t) *p)
  4340.                 {
  4341.                 case jump_n:
  4342.                   is_a_jump_n = true;
  4343.                 case maybe_pop_jump:
  4344.                 case pop_failure_jump:
  4345.                 case jump:
  4346.                   p1 = p + 1;
  4347.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4348.                   p1 += mcnt;    
  4349.  
  4350.                   if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
  4351.                       || (!is_a_jump_n
  4352.                           && (re_opcode_t) *p1 == on_failure_jump))
  4353.                     goto fail;
  4354.                   break;
  4355.                 default:
  4356.                   /* do nothing */ ;
  4357.                 }
  4358.             }
  4359.  
  4360.           if (d >= string1 && d <= end1)
  4361.         dend = end_match_1;
  4362.         }
  4363.       else
  4364.         break;   /* Matching at this starting point really fails.  */
  4365.     } /* for (;;) */
  4366.  
  4367.   if (best_regs_set)
  4368.     goto restore_best_regs;
  4369.  
  4370.   FREE_VARIABLES ();
  4371.  
  4372.   return -1;                     /* Failure to match.  */
  4373. } /* re_match_2 */
  4374.  
  4375. /* Subroutine definitions for re_match_2.  */
  4376.  
  4377.  
  4378. /* We are passed P pointing to a register number after a start_memory.
  4379.    
  4380.    Return true if the pattern up to the corresponding stop_memory can
  4381.    match the empty string, and false otherwise.
  4382.    
  4383.    If we find the matching stop_memory, sets P to point to one past its number.
  4384.    Otherwise, sets P to an undefined byte less than or equal to END.
  4385.  
  4386.    We don't handle duplicates properly (yet).  */
  4387.  
  4388. static boolean
  4389. group_match_null_string_p (
  4390.     unsigned char **p, unsigned char *end,
  4391.     register_info_type *reg_info)
  4392. {
  4393.   int mcnt;
  4394.   /* Point to after the args to the start_memory.  */
  4395.   unsigned char *p1 = *p + 2;
  4396.   
  4397.   while (p1 < end)
  4398.     {
  4399.       /* Skip over opcodes that can match nothing, and return true or
  4400.      false, as appropriate, when we get to one that can't, or to the
  4401.          matching stop_memory.  */
  4402.       
  4403.       switch ((re_opcode_t) *p1)
  4404.         {
  4405.         /* Could be either a loop or a series of alternatives.  */
  4406.         case on_failure_jump:
  4407.           p1++;
  4408.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4409.           
  4410.           /* If the next operation is not a jump backwards in the
  4411.          pattern.  */
  4412.  
  4413.       if (mcnt >= 0)
  4414.         {
  4415.               /* Go through the on_failure_jumps of the alternatives,
  4416.                  seeing if any of the alternatives cannot match nothing.
  4417.                  The last alternative starts with only a jump,
  4418.                  whereas the rest start with on_failure_jump and end
  4419.                  with a jump, e.g., here is the pattern for `a|b|c':
  4420.  
  4421.                  /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
  4422.                  /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
  4423.                  /exactn/1/c                        
  4424.  
  4425.                  So, we have to first go through the first (n-1)
  4426.                  alternatives and then deal with the last one separately.  */
  4427.  
  4428.  
  4429.               /* Deal with the first (n-1) alternatives, which start
  4430.                  with an on_failure_jump (see above) that jumps to right
  4431.                  past a jump_past_alt.  */
  4432.  
  4433.               while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
  4434.                 {
  4435.                   /* `mcnt' holds how many bytes long the alternative
  4436.                      is, including the ending `jump_past_alt' and
  4437.                      its number.  */
  4438.  
  4439.                   if (!alt_match_null_string_p (p1, p1 + mcnt - 3, 
  4440.                                       reg_info))
  4441.                     return false;
  4442.  
  4443.                   /* Move to right after this alternative, including the
  4444.              jump_past_alt.  */
  4445.                   p1 += mcnt;    
  4446.  
  4447.                   /* Break if it's the beginning of an n-th alternative
  4448.                      that doesn't begin with an on_failure_jump.  */
  4449.                   if ((re_opcode_t) *p1 != on_failure_jump)
  4450.                     break;
  4451.         
  4452.           /* Still have to check that it's not an n-th
  4453.              alternative that starts with an on_failure_jump.  */
  4454.           p1++;
  4455.                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4456.                   if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
  4457.                     {
  4458.               /* Get to the beginning of the n-th alternative.  */
  4459.                       p1 -= 3;
  4460.                       break;
  4461.                     }
  4462.                 }
  4463.  
  4464.               /* Deal with the last alternative: go back and get number
  4465.                  of the `jump_past_alt' just before it.  `mcnt' contains
  4466.                  the length of the alternative.  */
  4467.               EXTRACT_NUMBER (mcnt, p1 - 2);
  4468.  
  4469.               if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
  4470.                 return false;
  4471.  
  4472.               p1 += mcnt;    /* Get past the n-th alternative.  */
  4473.             } /* if mcnt > 0 */
  4474.           break;
  4475.  
  4476.           
  4477.         case stop_memory:
  4478.       assert (p1[1] == **p);
  4479.           *p = p1 + 2;
  4480.           return true;
  4481.  
  4482.         
  4483.         default: 
  4484.           if (!common_op_match_null_string_p (&p1, end, reg_info))
  4485.             return false;
  4486.         }
  4487.     } /* while p1 < end */
  4488.  
  4489.   return false;
  4490. } /* group_match_null_string_p */
  4491.  
  4492.  
  4493. /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
  4494.    It expects P to be the first byte of a single alternative and END one
  4495.    byte past the last. The alternative can contain groups.  */
  4496.    
  4497. static boolean
  4498. alt_match_null_string_p (
  4499.     unsigned char *p, unsigned char *end,
  4500.     register_info_type *reg_info)
  4501. {
  4502.   int mcnt;
  4503.   unsigned char *p1 = p;
  4504.   
  4505.   while (p1 < end)
  4506.     {
  4507.       /* Skip over opcodes that can match nothing, and break when we get 
  4508.          to one that can't.  */
  4509.       
  4510.       switch ((re_opcode_t) *p1)
  4511.         {
  4512.     /* It's a loop.  */
  4513.         case on_failure_jump:
  4514.           p1++;
  4515.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4516.           p1 += mcnt;
  4517.           break;
  4518.           
  4519.     default: 
  4520.           if (!common_op_match_null_string_p (&p1, end, reg_info))
  4521.             return false;
  4522.         }
  4523.     }  /* while p1 < end */
  4524.  
  4525.   return true;
  4526. } /* alt_match_null_string_p */
  4527.  
  4528.  
  4529. /* Deals with the ops common to group_match_null_string_p and
  4530.    alt_match_null_string_p.  
  4531.    
  4532.    Sets P to one after the op and its arguments, if any.  */
  4533.  
  4534. static boolean
  4535. common_op_match_null_string_p (
  4536.     unsigned char **p, unsigned char *end,
  4537.     register_info_type *reg_info)
  4538. {
  4539.   int mcnt;
  4540.   boolean ret;
  4541.   int reg_no;
  4542.   unsigned char *p1 = *p;
  4543.  
  4544.   switch ((re_opcode_t) *p1++)
  4545.     {
  4546.     case no_op:
  4547.     case begline:
  4548.     case endline:
  4549.     case begbuf:
  4550.     case endbuf:
  4551.     case wordbeg:
  4552.     case wordend:
  4553.     case wordbound:
  4554.     case notwordbound:
  4555. #ifdef emacs
  4556.     case before_dot:
  4557.     case at_dot:
  4558.     case after_dot:
  4559. #endif
  4560.       break;
  4561.  
  4562.     case start_memory:
  4563.       reg_no = *p1;
  4564.       assert (reg_no > 0 && reg_no <= MAX_REGNUM);
  4565.       ret = group_match_null_string_p (&p1, end, reg_info);
  4566.       
  4567.       /* Have to set this here in case we're checking a group which
  4568.          contains a group and a back reference to it.  */
  4569.  
  4570.       if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
  4571.         REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
  4572.  
  4573.       if (!ret)
  4574.         return false;
  4575.       break;
  4576.           
  4577.     /* If this is an optimized succeed_n for zero times, make the jump.  */
  4578.     case jump:
  4579.       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4580.       if (mcnt >= 0)
  4581.         p1 += mcnt;
  4582.       else
  4583.         return false;
  4584.       break;
  4585.  
  4586.     case succeed_n:
  4587.       /* Get to the number of times to succeed.  */
  4588.       p1 += 2;        
  4589.       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4590.  
  4591.       if (mcnt == 0)
  4592.         {
  4593.           p1 -= 4;
  4594.           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
  4595.           p1 += mcnt;
  4596.         }
  4597.       else
  4598.         return false;
  4599.       break;
  4600.  
  4601.     case duplicate: 
  4602.       if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
  4603.         return false;
  4604.       break;
  4605.  
  4606.     case set_number_at:
  4607.       p1 += 4;
  4608.  
  4609.     default:
  4610.       /* All other opcodes mean we cannot match the empty string.  */
  4611.       return false;
  4612.   }
  4613.  
  4614.   *p = p1;
  4615.   return true;
  4616. } /* common_op_match_null_string_p */
  4617.  
  4618.  
  4619. /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
  4620.    bytes; nonzero otherwise.  */
  4621.    
  4622. static int
  4623. bcmp_translate (
  4624.      unsigned char *s1, unsigned char *s2,
  4625.      register int len,
  4626.      char *translate)
  4627. {
  4628.   register unsigned char *p1 = s1, *p2 = s2;
  4629.   while (len)
  4630.     {
  4631.       if (translate[*p1++] != translate[*p2++]) return 1;
  4632.       len--;
  4633.     }
  4634.   return 0;
  4635. }
  4636.  
  4637. /* Entry points for GNU code.  */
  4638.  
  4639. /* re_compile_pattern is the GNU regular expression compiler: it
  4640.    compiles PATTERN (of length SIZE) and puts the result in BUFP.
  4641.    Returns 0 if the pattern was valid, otherwise an error string.
  4642.    
  4643.    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
  4644.    are set in BUFP on entry.
  4645.    
  4646.    We call regex_compile to do the actual compilation.  */
  4647.  
  4648. const char *
  4649. re_compile_pattern (pattern, length, bufp)
  4650.      const char *pattern;
  4651.      int length;
  4652.      struct re_pattern_buffer *bufp;
  4653. {
  4654.   reg_errcode_t ret;
  4655.   
  4656.   /* GNU code is written to assume at least RE_NREGS registers will be set
  4657.      (and at least one extra will be -1).  */
  4658.   bufp->regs_allocated = REGS_UNALLOCATED;
  4659.   
  4660.   /* And GNU code determines whether or not to get register information
  4661.      by passing null for the REGS argument to re_match, etc., not by
  4662.      setting no_sub.  */
  4663.   bufp->no_sub = 0;
  4664.   
  4665.   /* Match anchors at newline.  */
  4666.   bufp->newline_anchor = 1;
  4667.   
  4668.   ret = regex_compile (pattern, length, re_syntax_options, bufp);
  4669.  
  4670.   return re_error_msg[(int) ret];
  4671. }     
  4672.  
  4673. /* Entry points compatible with 4.2 BSD regex library.  We don't define
  4674.    them if this is an Emacs or POSIX compilation.  */
  4675.  
  4676. #if !defined (emacs) && !defined (_POSIX_SOURCE)
  4677.  
  4678. /* BSD has one and only one pattern buffer.  */
  4679. static struct re_pattern_buffer re_comp_buf;
  4680.  
  4681. char *
  4682. re_comp (s)
  4683.     const char *s;
  4684. {
  4685.   reg_errcode_t ret;
  4686.   
  4687.   if (!s)
  4688.     {
  4689.       if (!re_comp_buf.buffer)
  4690.     return "No previous regular expression";
  4691.       return 0;
  4692.     }
  4693.  
  4694.   if (!re_comp_buf.buffer)
  4695.     {
  4696.       re_comp_buf.buffer = (unsigned char *) malloc (200);
  4697.       if (re_comp_buf.buffer == NULL)
  4698.         return "Memory exhausted";
  4699.       re_comp_buf.allocated = 200;
  4700.  
  4701.       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
  4702.       if (re_comp_buf.fastmap == NULL)
  4703.     return "Memory exhausted";
  4704.     }
  4705.  
  4706.   /* Since `re_exec' always passes NULL for the `regs' argument, we
  4707.      don't need to initialize the pattern buffer fields which affect it.  */
  4708.  
  4709.   /* Match anchors at newlines.  */
  4710.   re_comp_buf.newline_anchor = 1;
  4711.  
  4712.   ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
  4713.   
  4714.   /* Yes, we're discarding `const' here.  */
  4715.   return (char *) re_error_msg[(int) ret];
  4716. }
  4717.  
  4718.  
  4719. int
  4720. re_exec (s)
  4721.     const char *s;
  4722. {
  4723.   const int len = strlen (s);
  4724.   return
  4725.     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
  4726. }
  4727. #endif /* not emacs and not _POSIX_SOURCE */
  4728.  
  4729. /* POSIX.2 functions.  Don't define these for Emacs.  */
  4730.  
  4731. #ifndef emacs
  4732.  
  4733. /* regcomp takes a regular expression as a string and compiles it.
  4734.  
  4735.    PREG is a regex_t *.  We do not expect any fields to be initialized,
  4736.    since POSIX says we shouldn't.  Thus, we set
  4737.  
  4738.      `buffer' to the compiled pattern;
  4739.      `used' to the length of the compiled pattern;
  4740.      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
  4741.        REG_EXTENDED bit in CFLAGS is set; otherwise, to
  4742.        RE_SYNTAX_POSIX_BASIC;
  4743.      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
  4744.      `fastmap' and `fastmap_accurate' to zero;
  4745.      `re_nsub' to the number of subexpressions in PATTERN.
  4746.  
  4747.    PATTERN is the address of the pattern string.
  4748.  
  4749.    CFLAGS is a series of bits which affect compilation.
  4750.  
  4751.      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
  4752.      use POSIX basic syntax.
  4753.  
  4754.      If REG_NEWLINE is set, then . and [^...] don't match newline.
  4755.      Also, regexec will try a match beginning after every newline.
  4756.  
  4757.      If REG_ICASE is set, then we considers upper- and lowercase
  4758.      versions of letters to be equivalent when matching.
  4759.  
  4760.      If REG_NOSUB is set, then when PREG is passed to regexec, that
  4761.      routine will report only success or failure, and nothing about the
  4762.      registers.
  4763.  
  4764.    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
  4765.    the return codes and their meanings.)  */
  4766.  
  4767. int
  4768. regcomp (preg, pattern, cflags)
  4769.     regex_t *preg;
  4770.     const char *pattern; 
  4771.     int cflags;
  4772. {
  4773.   reg_errcode_t ret;
  4774.   unsigned syntax
  4775.     = (cflags & REG_EXTENDED) ?
  4776.       RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
  4777.  
  4778.   /* regex_compile will allocate the space for the compiled pattern.  */
  4779.   preg->buffer = 0;
  4780.   preg->allocated = 0;
  4781.   preg->used = 0;
  4782.   
  4783.   /* Don't bother to use a fastmap when searching.  This simplifies the
  4784.      REG_NEWLINE case: if we used a fastmap, we'd have to put all the
  4785.      characters after newlines into the fastmap.  This way, we just try
  4786.      every character.  */
  4787.   preg->fastmap = 0;
  4788.   
  4789.   if (cflags & REG_ICASE)
  4790.     {
  4791.       unsigned i;
  4792.       
  4793.       preg->translate = (char *) malloc (CHAR_SET_SIZE);
  4794.       if (preg->translate == NULL)
  4795.         return (int) REG_ESPACE;
  4796.  
  4797.       /* Map uppercase characters to corresponding lowercase ones.  */
  4798.       for (i = 0; i < CHAR_SET_SIZE; i++)
  4799.         preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
  4800.     }
  4801.   else
  4802.     preg->translate = NULL;
  4803.  
  4804.   /* If REG_NEWLINE is set, newlines are treated differently.  */
  4805.   if (cflags & REG_NEWLINE)
  4806.     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
  4807.       syntax &= ~RE_DOT_NEWLINE;
  4808.       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
  4809.       /* It also changes the matching behavior.  */
  4810.       preg->newline_anchor = 1;
  4811.     }
  4812.   else
  4813.     preg->newline_anchor = 0;
  4814.  
  4815.   preg->no_sub = !!(cflags & REG_NOSUB);
  4816.  
  4817.   /* POSIX says a null character in the pattern terminates it, so we 
  4818.      can use strlen here in compiling the pattern.  */
  4819.   ret = regex_compile (pattern, strlen (pattern), syntax, preg);
  4820.   
  4821.   /* POSIX doesn't distinguish between an unmatched open-group and an
  4822.      unmatched close-group: both are REG_EPAREN.  */
  4823.   if (ret == REG_ERPAREN) ret = REG_EPAREN;
  4824.   
  4825.   return (int) ret;
  4826. }
  4827.  
  4828.  
  4829. /* regexec searches for a given pattern, specified by PREG, in the
  4830.    string STRING.
  4831.    
  4832.    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
  4833.    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
  4834.    least NMATCH elements, and we set them to the offsets of the
  4835.    corresponding matched substrings.
  4836.    
  4837.    EFLAGS specifies `execution flags' which affect matching: if
  4838.    REG_NOTBOL is set, then ^ does not match at the beginning of the
  4839.    string; if REG_NOTEOL is set, then $ does not match at the end.
  4840.    
  4841.    We return 0 if we find a match and REG_NOMATCH if not.  */
  4842.  
  4843. int
  4844. regexec (preg, string, nmatch, pmatch, eflags)
  4845.     const regex_t *preg;
  4846.     const char *string; 
  4847.     size_t nmatch; 
  4848.     regmatch_t pmatch[]; 
  4849.     int eflags;
  4850. {
  4851.   int ret;
  4852.   struct re_registers regs;
  4853.   regex_t private_preg;
  4854.   int len = strlen (string);
  4855.   boolean want_reg_info = !preg->no_sub && nmatch > 0;
  4856.  
  4857.   private_preg = *preg;
  4858.   
  4859.   private_preg.not_bol = !!(eflags & REG_NOTBOL);
  4860.   private_preg.not_eol = !!(eflags & REG_NOTEOL);
  4861.   
  4862.   /* The user has told us exactly how many registers to return
  4863.      information about, via `nmatch'.  We have to pass that on to the
  4864.      matching routines.  */
  4865.   private_preg.regs_allocated = REGS_FIXED;
  4866.   
  4867.   if (want_reg_info)
  4868.     {
  4869.       regs.num_regs = nmatch;
  4870.       regs.start = TALLOC (nmatch, regoff_t);
  4871.       regs.end = TALLOC (nmatch, regoff_t);
  4872.       if (regs.start == NULL || regs.end == NULL)
  4873.         return (int) REG_NOMATCH;
  4874.     }
  4875.  
  4876.   /* Perform the searching operation.  */
  4877.   ret = re_search (&private_preg, string, len,
  4878.                    /* start: */ 0, /* range: */ len,
  4879.                    want_reg_info ? ®s : (struct re_registers *) 0);
  4880.   
  4881.   /* Copy the register information to the POSIX structure.  */
  4882.   if (want_reg_info)
  4883.     {
  4884.       if (ret >= 0)
  4885.         {
  4886.           unsigned r;
  4887.  
  4888.           for (r = 0; r < nmatch; r++)
  4889.             {
  4890.               pmatch[r].rm_so = regs.start[r];
  4891.               pmatch[r].rm_eo = regs.end[r];
  4892.             }
  4893.         }
  4894.  
  4895.       /* If we needed the temporary register info, free the space now.  */
  4896.       free (regs.start);
  4897.       free (regs.end);
  4898.     }
  4899.  
  4900.   /* We want zero return to mean success, unlike `re_search'.  */
  4901.   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
  4902. }
  4903.  
  4904.  
  4905. /* Returns a message corresponding to an error code, ERRCODE, returned
  4906.    from either regcomp or regexec.   We don't use PREG here.  */
  4907.  
  4908. #pragma argsused
  4909. size_t
  4910. regerror (
  4911.     int errcode,
  4912.     const regex_t *preg,
  4913.     char *errbuf,
  4914.     size_t errbuf_size)
  4915. {
  4916.   const char *msg;
  4917.   size_t msg_size;
  4918.  
  4919.   if (errcode < 0
  4920.       || errcode >= (sizeof (re_error_msg) / sizeof (re_error_msg[0])))
  4921.     /* Only error codes returned by the rest of the code should be passed 
  4922.        to this routine.  If we are given anything else, or if other regex
  4923.        code generates an invalid error code, then the program has a bug.
  4924.        Dump core so we can fix it.  */
  4925.     abort ();
  4926.  
  4927.   msg = re_error_msg[errcode];
  4928.  
  4929.   /* POSIX doesn't require that we do anything in this case, but why
  4930.      not be nice.  */
  4931.   if (! msg)
  4932.     msg = "Success";
  4933.  
  4934.   msg_size = strlen (msg) + 1; /* Includes the null.  */
  4935.   
  4936.   if (errbuf_size != 0)
  4937.     {
  4938.       if (msg_size > errbuf_size)
  4939.         {
  4940.           strncpy (errbuf, msg, errbuf_size - 1);
  4941.           errbuf[errbuf_size - 1] = 0;
  4942.         }
  4943.       else
  4944.         strcpy (errbuf, msg);
  4945.     }
  4946.  
  4947.   return msg_size;
  4948. }
  4949.  
  4950.  
  4951. /* Free dynamically allocated space used by PREG.  */
  4952.  
  4953. void
  4954. regfree (
  4955.     regex_t *preg)
  4956. {
  4957.   if (preg->buffer != NULL)
  4958.     free (preg->buffer);
  4959.   preg->buffer = NULL;
  4960.   
  4961.   preg->allocated = 0;
  4962.   preg->used = 0;
  4963.  
  4964.   if (preg->fastmap != NULL)
  4965.     free (preg->fastmap);
  4966.   preg->fastmap = NULL;
  4967.   preg->fastmap_accurate = 0;
  4968.  
  4969.   if (preg->translate != NULL)
  4970.     free (preg->translate);
  4971.   preg->translate = NULL;
  4972. }
  4973.  
  4974. #endif /* not emacs  */
  4975.  
  4976. /*
  4977. Local variables:
  4978. make-backup-files: t
  4979. version-control: t
  4980. trim-versions-without-asking: nil
  4981. End:
  4982. */
  4983.